DEV Community

Discussion on: React Hooks - useContext with multiple context

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>
}