DEV Community

Cover image for React Context and Hooks: Pass data and update it easily
Nihar Raote
Nihar Raote

Posted on • Originally published at

React Context and Hooks: Pass data and update it easily

In the previous article, we looked at what Context is and how to pass values with it. In this article we will look at updating the Context value from the child component. For our theme example this means clicking the button will now switch the theme between light and dark.

Updating Context value

In the previous article, we directly passed the theme via the Provider component. Although the value is passed to ThemeButton.js and ThemeWindow.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. To do this, we can create a stateful object which will contain both the theme and a function. This way React can keep track of the theme and perform the necessary re-renders when it updates.

Creating a stateful object

This is pretty straightforward. A stateful object containing a theme type and a function is passed via the Provider component. While the ThemeWindow component only needs minor changes, we do need to implement the function in the ThemeButton component.

Implementing theme switch function

Nothing special needs to be done to implement the function. Calling it when the button is pressed will switch the theme.

Implementing theme switch function

As easy as that. When this button is clicked, the switchTheme() function will be executed. This will update the stateful value and thus trigger a re-render. And finally, the updated theme will be rendered in the ThemeWindow component.

Minor changes in ThemeWindow

Wrapping up

This was the conclusion to the previous article about React Context. As you have seen, React Context is a powerful tool.

However, this simple example does not really showcase its power. In complex applications with dozens of components, where values and state need to be passed to several different components, React Context will make this job far easier than regular props.

Top comments (0)