React Context API is one of the best ways to share common data between components in a React application. We can easily pass a single value in the React context. But the question remains on how to pass multiple values in React Context?
To pass multiple values in React Context, we can use the Provider API. Also, we can easily consume the context data by utilizing the useContext React Hook. However, it is important to understand the basic syntax and approach behind this.
To get a better idea, let us look at a simple example.
1 – React Context Multiple Values Example
The React Context Provider component accepts a value prop as input. We can pass anything we want to the value prop.
In other words, React Context can easily handle multiple values.
For example, we can have a Context Provider with multiple values as below:
const CounterContext = React.createContext("counter")
export default function MultiValueContextDemo() {
const [counter1, setCounter1] = useState(0);
const [counter2, setCounter2] = useState(0);
return(
<CounterContext.Provider value={{ counter1, setCounter1, counter2, setCounter2 }}>
<CounterComponent />
</CounterContext.Provider>
)
}
In the above example, we create the CounterContext using React.createContext() method.
We pass multiple values to React Context Provider in the form of counter1 and counter2. We also pass methods setCounter1 and setCounter2 to set the value of these counter variables so that the context consumer can use these methods.
Now, we can simply consume the values from the context by utilizing the useContext Hook. See below:
const CounterComponent = () => {
const {counter1, setCounter1, counter2, setCounter2 } = useContext(CounterContext)
return(
<React.Fragment>
<button onClick={() => setCounter1((counter) => counter + 1)}>Click Counter {counter1}</button>
<button onClick={() => setCounter2((counter) => counter + 1)}>Click Counter {counter2}</button>
</React.Fragment>
)
}
As you can see, the useContext hook returns the counter values to the child component. In the button click event, we use the setCounter methods to increment the value of the counter variables.
When you click the buttons, you will see the counter values going up by 1 for every click.
Conclusion
With this, we have learnt how to pass multiple values in React Context.
Basically, the value prop for the Provider component can accept any types of values. We can easily leverage this to pass variables as well as functions to the value prop. Whatever we pass as input will be available when we consume the context in a child component.
Want to learn more about React Context? Check out this detailed post on React Context with Class Components.
If you have any comments or queries about this post, please mention them in the comments section below.
0 Comments