I would like to set the context at runtime after some networking call is complete (only then do I know the value which needs to be accessible throughout my app), but I don't know how to persist this value.
I can update the context value like so:
<NetworkVersion.Provider value={{version: this.state.version}}>
where I can use the state of the component. This approach has been taken from the official React docs.
but I was surprised to find out that other Consumers of this Provider get the default value (an empty object) which was initialised in the React.createContext() call. Is there a way to update the Context at runtime and keep that value for the lifetime of the app?
Updating Context value js components, we cannot update this value. To switch between the two theme types, we need to pass a function as well. This function will allow us to switch between both themes. So we need to pass this function along with the dark theme via the Provider component.
The useContext is the React hook, used in context API to consume the context state or object. There are two options for getting the context object. We can get the context object from Context Consumer or useContext Hook. UseContext Hook is an exquisite, more excellent way to get the context object with less code.
🧐 Re-renders reason: context changesWhen the value in Context Provider changes, all components that use this Context will re-render, even if they don't use the changed portion of the data directly.
Make sure your Context Consumer is a child of the associated Provider, otherwise it will just get the default value. See https://reactjs.org/docs/context.html#consumer
You'd also be better to pass a primitive value - i.e.
<NetworkVersion.Provider value={this.state.version}>
or you may get unnecessary re-renders. See https://reactjs.org/docs/context.html#caveats
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With