Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Context API, updating context

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?

like image 568
dentemm Avatar asked Apr 19 '18 14:04

dentemm


People also ask

How do you update a value in context in React js?

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.

Is context API and useContext same?

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.

Does New React context API trigger re renders?

🧐 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.


Video Answer


1 Answers

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

like image 107
Greg Avatar answered Oct 13 '22 11:10

Greg