Hooks 3: useMemo useCallback


useMemo

A copy of object will not re-render whenever param is updated.


const copy = useMemo(() => {return obj},[])
const provider = useMemo(() =>
    new OpenStreetMapProvider(),[])
    

useCallback

A copy of function will not re-render whenever param is updated.


const handle = useCallback((e) => {//do sth}, [])
const handleClickMap = useCallback((e) => {
        if (geomode === "Geolocation"){
            const {lat,lng} = e.latlng;
            dispatch({type:'value',key:'sLat',value:lat})
            dispatch({type:'value',key:'sLng',value:lng})
            map.setView(e.latlng,travelmode==="foot"?13:12)
        }
    },[geomode,map,travelmode,dispatch])

    

They are often called inside useEffect. Their purpose is to avoid re-rendering whenever useEffect re-renders sth.


useEffect(()=>{
    if (map){
        map.on('click',handleClickMap);
        return () => map.off('click',handleClickMap)
    }
},[map,handleClickMap])
useEffect(() => {
    window.addEventListener("keydown", handleUserKeyPress);
    return () => {
        window.removeEventListener("keydown", handleUserKeyPress);
    };
}, [handleUserKeyPress]);
    

References