Optimize rerenders

Open in CodeSandbox

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
        <script crossorigin src="https://cdn.jsdelivr.net/npm/react@17/umd/react.production.min.js"></script>
        <script crossorigin src="https://cdn.jsdelivr.net/npm/react-dom@17/umd/react-dom.production.min.js"></script>
        <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
        <!-- To make the map appear, you must add your apikey -->
        <script src="https://js.api.mappable.world/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

        <script
            data-plugins="transform-modules-umd"
            data-presets="typescript"
            type="text/babel"
            src="../variables.ts"
        ></script>
        <script
            data-plugins="transform-modules-umd"
            data-presets="typescript"
            type="text/babel"
            src="./common.ts"
        ></script>
        <script data-plugins="transform-modules-umd" data-presets="react, typescript" type="text/babel">
            import {CITY_1, CITY_2} from '../variables';
            import type {LngLat} from '@mappable-world/mappable-types';
            
            window.map = null;
            
            main();
            async function main() {
                // For each object in the JS API, there is a React counterpart
                // To use the React version of the API, include the module @mappable-world/mappable-reactify
                const [mappableReact] = await Promise.all([mappable.import('@mappable-world/mappable-reactify'), mappable.ready]);
                const reactify = mappableReact.reactify.bindTo(React, ReactDOM);
                const {MMap, MMapDefaultSchemeLayer, MMapDefaultFeaturesLayer, MMapControls, MMapControlButton} =
                    reactify.module(mappable);
            
                const {MMapZoomControl, MMapDefaultMarker} = reactify.module(
                    await mappable.import('@mappable-world/mappable-default-ui-theme')
                );
            
                /** Returns `coords` shifted by `diff`. Always returns new array to illustrate rerender related problems. */
                function shift(coords: LngLat, diff: LngLat): LngLat {
                    return [coords[0] + diff[0], coords[1] + diff[1]];
                }
            
                function App() {
                    const [location, setLocation] = React.useState<{center: LngLat; zoom: number; duration?: number}>(
                        CITY_1.location
                    );
                    const [counter, setCounter] = React.useState(0);
            
                    return (
                        /* Initialize the map and pass initialization parameters */
                        <MMap location={reactify.useDefault(location, [location])} ref={(x) => (map = x)}>
                            {/* Add a map scheme layer */}
                            <MMapDefaultSchemeLayer />
                            <MMapDefaultFeaturesLayer />
            
                            {/* MMapZoomControl sets map's `location`. Our state `location` doesn't know anything about it */}
                            <MMapControls position="right">
                                <MMapZoomControl />
                            </MMapControls>
            
                            <MMapControls position="top">
                                {/* Set map location with animation */}
                                <MMapControlButton
                                    text={CITY_1.name}
                                    onClick={() => setLocation({...CITY_1.location, duration: 1000})}
                                />
                                {/* Set map location. Create a copy of object to trigger `update` */}
                                <MMapControlButton text={CITY_2.name} onClick={() => setLocation({...CITY_2.location})} />
                                {/* Trigger rerender */}
                                <MMapControlButton text={`Rerender! ${counter}`} onClick={() => setCounter((x) => x + 1)} />
                            </MMapControls>
            
                            {/* Any rerender will update coordinates */}
                            <MMapDefaultMarker
                                size="normal"
                                coordinates={shift(location.center, [-0.05, -0.05])}
                                draggable
                                title="without useDefault"
                                color="pink"
                            />
                            {/* Only rerenders with changed `location.center` will update coordinates */}
                            <MMapDefaultMarker
                                size="normal"
                                coordinates={reactify.useDefault(shift(location.center, [0.05, 0.05]), [location.center])}
                                draggable
                                title="with useDefault"
                            />
                        </MMap>
                    );
                }
            
                ReactDOM.render(
                    <React.StrictMode>
                        <App />
                    </React.StrictMode>,
                    document.getElementById('app')
                );
            }
        </script>

        <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
        <link rel="stylesheet" href="./common.css" />
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>
import type {LngLat} from '@mappable-world/mappable-types';

export const CITY_1 = {
    name: 'Dubai',
    location: {
        center: [55.2744, 25.1972] as LngLat,
        zoom: 12
    }
};

export const CITY_2 = {
    name: 'Abu Dhabi',
    location: {
        center: [54.4366, 24.4604] as LngLat,
        zoom: 11
    }
};
mappable.ready.then(() => {
    mappable.import.registerCdn('https://cdn.jsdelivr.net/npm/{package}', ['@mappable-world/mappable-default-ui-theme@0.0'])
});