How to update state in Context in React.js without having the component re-render?
P粉322319601
P粉322319601 2024-02-26 00:05:17
0
1
423

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粉322319601
P粉322319601

reply all(1)
P粉590428357

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!