So basically I'm using the Google Maps API and when I click on a building it displays a modal with some information. The mode's state is in the context and updated via click events on the map. What happens is that when the state updates, it re-renders the entire Map again (making it smaller) because the state is updated from the Map component itself. How can I update the context state but not have the map re-render?
I tried using memo and useCallback but since the props are being updated (context) it re-renders the map again.
P粉5904283572024-02-26 16:12:50
If your map uses values from a context that changes frequently, there is no way to prevent re-rendering. If you do that, it won't work anymore
useContext(Context) makes your component re-render when the value in the provider changes. No matter what you use in the component's context, it will re-render if you use useContext . You can't prevent this, that's how context works. However, if your component uses something in the context that doesn't change frequently, there are techniques you can use to stop re-rendering.
Create new components that use the components you want to remember. The context is called there. Pass it as a prop to your component. Use React.memo on your components. But you have to make sure that all properties passed to the component are remembered.
Also, you can use the second parameter in the memo to exclude content that does not retain references between renders (not recommended if you don't know what you are doing, it may cause shutdown issues)
const YourComponent = React.memo(({someContextValue}) => ...) const YourNewComponent = () => { const {someContextValue} = useContext(SomeContext) // here someContextValue is a thing that does not change its value often return}
Then you must use YourNewComponent instead of your component