I have a map which has an overlay. I have an effect which, when the underlying data changes, deletes the old overlay and re-draws a new one.
Of note, I\'m using \"
To add onto @DamienFlury's solution, Another technique you can use to remove a constantly changing dependency from the dependency array is to use the useReducer hook. This allows you to decouple your state variables from your effects
function reducer(state, action){
if(action.type === 'UPDATE_OVERLAY'){
return {
...state,
overlay: action.newOverlay, //update overlay on your state object
}
} else {
return state;
}
}
function YourComponent(yourProps){
const [ state, dispatch ] = useReducer(reducer, initialState);
// Other functions
useEffect(() => {
// remove the overlay if it is there,
if (overlay) map.removeOverlays(overlay);
// Generate the new overlay based on the new data (useCallback function)
const newOverlay = generateNewOverlay(data)
// this also allows you to decouple your state changes from your effects!
dispatch({
type: 'UPDATE_OVERLAY',
newOverlay,
});
// Show the new overlay on my map
map.addOverlays(newOverlay);
}, [dispatch, map, data, generateNewOverlay]);
}
Note that I have added dispatch to the dependency array just as a good practice, You should never lie about your dependencies!. React guarantees the dispatch function to be constant throughout the component lifetime.