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

and Example video

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)

bdbch profile image
bdbch • Edited

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



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

    // rest of your app
), 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>