DEV Community

Rajesh Jain
Rajesh Jain

Posted on

React Hooks - useContext with multiple context

Here is my question/confusion.

I am following some code examples to create GlobalState and then use the react Hooks useContext to access the state.

here is the example code
https://github.com/academind/react-redux-vs-context/blob/context-hooks/src/context/GlobalState.js

and Example video
https://www.youtube.com/watch?v=R_7XRX7nLsw

My question is, if I have multiple components, each trying to access the global state, do I create a global context or do I create multiple context. And then how do I use the provider and consumer if I have multiple context.

Top comments (1)

Collapse
 
bdbch profile image
bdbch • Edited

You should create one globalContext and pass that globalContext to your different Components.

Example:

context.js

import { createContext } from 'react'

export const NameContext = createContext('John Doe')

Now you need to wrap your application with the Provider:

// your imports here
import { NameContext } from './context.js'

// do react setup stuff

ReactDOM.render((
  <NameContext.Provider>
    // rest of your app
  </NameContext.Provider>
), document.getElementById('root')

Now use useContext in your components like this:

import React, { useContext } from 'react'
import { NameContext } from './context.js'

const MyComponent = () => {
  // now your name is available in the component
  // and will also work in all other components like this
  // with just one context
  const name = useContext(NameContext)

  return <div>{name}</div>
}