Discussion on: React Hooks - useContext with multiple context

bdbch profile image
Dominik Biedebach

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>