Intro to React useContext Hook

Intro to React useContext Hook

React's useContext lets you share data between your components

ยท

2 min read

In React, context lets you pass data from a parent component down the component tree to its children components, without having to manually pass props down at each level. The useContext hook lets any component in the component tree read and subscribe to context if needed. The component rerenders when the closest parent component with <YourContext.Provider> updates, and the context value changes.

First, we import createContext from React:

import { createContext } from 'react'

Next, let's create some context or data that we want to share throughout our application:

import { createContext } from 'react'

const actionContext = {
  swim:'๐ŸŠ๐Ÿพ',
  climb:'๐Ÿง—๐Ÿพ',
  bike:'๐Ÿšด๐Ÿฟ'
}

In this example, we use an object and key-value pairs, for the context. The key 'swim' for the value ๐ŸŠ๐Ÿพ, (person swimming emoji), the key 'climb' for the value ๐Ÿง—๐Ÿพ, (person climbing emoji), and the key 'bike' for the value ๐Ÿšด๐Ÿฟ, (person biking emoji).

Then we pass this context that we created to the createContext() function:

// rest of the code

// creates the context
const ActionContext = createContext(actionContext);

Now that we have created our context, we can pass it to the <Context.Provider>:

// rest of the code

export default function App() {
  return (
    /* provides the value for the context*/
    <ActionContext.Provider value={actionContext.swim}> 
      <Page />
    </ActionContext.Provider>
  )
}

Next, let's update the import at the top of the file and add the useContext() hook from React:

import { createContext, useContext } from 'react'

// rest of the code

Finally, we can use this context further down our application:

// rest of the code

function Page() {
  // lets you read or 'consume' context and subscribe to changes
  const value = useContext(ActionContext) 

  return (
    <p>
      I like to {value}. It is my favorite activity.
    </p>
  )
}

Now we can access the context within our components.

Putting it all together:

import { createContext, useContext } from 'react'

const actionContext = {
  swim:'๐ŸŠ๐Ÿพ',
  climb:'๐Ÿง—๐Ÿพ',
  bike:'๐Ÿšด๐Ÿฟ'
}

// creates the context
const ActionContext = createContext(actionContext) 

export default function App() {
  return (
    /* provides the value for the context*/
    <ActionContext.Provider value={actionContext.swim}> 
      <Page />
    </ActionContext.Provider>
  )
}

function Page() {
  // lets you read or 'consume' context and subscribe to changes
  const value = useContext(ActionContext) 

  return (
    <p>
      I like to {value}. It is my favorite activity.
    </p>
  )
}

Try adding context to a React project and let me know how it goes!

ย