DEV Community

SavvyShivam
SavvyShivam

Posted on

useContext in React

We use React Context to manage the state at a global level. Components can get data from the React context no matter how far down the components tree they are.

The very first step used in creating Context is to import “createContext

Context

Context lets the information be passed to the desired component without dragging it through multiple middle components and also when the same information is required by various components. It makes the parent component let certain information be available to any component in the component tree below it, without the use of repeated props.
The disadvantage of only passing props is that, in situations where the user would want two components’ state to change together and to do that the user will have to remove state from both of them, move it to their closest common parent, and then pass it down to them via props. But the closest common parent could be far away from the component, in the tree, that needs data. So lifting the state up that high could lead to a condition known as prop drilling.

createContext returns a context object. Components can read context by passing it to useContext().

useContext :

It is a React Hook that lets you read and accept a context.
To import this hook we need to write the following code in the top of the code file :

Instead of using useContext(ThemeContext) again and again in each component, we define a “Custom Hook” i.e. a function that does this for us called useTheme

We are now trying to create a simple program which will be able to change the color of the background and the text upon clicking a button.

The very first thing that we will do is create state variables and initialize the state of the state variable.
Here, we initialize the theme state variable to “white

In this next piece of code, to pass context to the children property, we will wrap it between the context provider and also pass the values “theme” and “setTheme”. When the children property is wrapped between the context Provider, that component now will be able to access the mentioned state variables.

The final step would be to export the useTheme and ThemeProvider

Now, in the App.js file we import the useTheme to be able to use it further into the program

Here, we create two context variables, with names theme and setTheme. The names of these variables are independent of the names of the variables used in the theme-context.js program.

The getStyle function returns a conditional statement where it’s programmed to change the state of the state variable according to the conditions mentioned.

Here by using the onClick event handler we update the theme and output the desired result.

Output :

The link for the entire code used above is given below:
https://codesandbox.io/s/use-context-i29vb5

Top comments (0)