Updating context in React
In this lesson we will look at updating components when the context value changes. Let's assume you want the context to change.
In this case, it is useful to use context in conjunction with states. Let's slightly modify our box app that we made in the last lesson and make it so that when the button is pressed, the transmitted value would be 'metal box :)'.
So, let's take our file App and after BigBox draw a button:
function App() {
return (
<MyContext.Provider value="small box :)">
<BigBox />
<button>click</button>
</MyContext.Provider>
);
}
Next, we import the hook useState and create a state name, the value of which will change when the button is pressed. Let's make its initial value the one that we immediately passed as the context value, that is, 'small box :)':
function App() {
const [name, setName] = useState('small box :)');
}
This time, we will pass the state name as context, not a string:
<MyContext.Provider value={name}>
<BigBox />
<button>click</button>
</MyContext.Provider>
As a final step, we will call the button click handler and use the setName function to set the new state value to 'metal box :)'. After that, we can click the button and check the result:
<button onClick={() => {
setName('metal box :)');
}}>click</button>
Use the application you created while solving the tasks for the previous lesson. Create a state age, which you will pass using the context from App instead of a number, set its initial value to 50. Add a button under the Parent component in App, each time you click on it, the value of the state age will decrease by 2.