How to update React Context
2 min readAug 2, 2020
In the previous article we saw how to setup context and also how to read state from context, in this article we will see how to update Context from any component, let’s begin
It is often necessary to update the context from a component that is nested somewhere deeply in the component tree. In this case you can pass a function down through the context to allow consumers to update the context:
Our Context setup it was like that
Lets add new film the list above, if you noticed we passed setFilms
as second argument to value, we can used it to update our state from child component,
- line 6 we destructuring
setFimls
fromStateContext
that we created earlier - line 7 we created state for holding user input
- line 28 we passed value from state that we created in like 7
- line 29 the function feeds all changes to state
- line 29 the function called when the user pressed enter : line 30 we used spread operator to get
prevState
and add new value toprevState
lets add a new film to the list
we successfully updated the films state