Intro to React Context

johnnyturco

Johnny Turco

Posted on January 9, 2023

Intro to React Context

React Context is a React hook that allows you to manage state globally. Per W3Schools, "[React Context] can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone." Instead of "prop drilling" (passing state via props through your component hierarchy), you can use Context to pass state through children components.

Getting Started: Creating Context

To get started, import createContext (and useState):

import { createContext, useState } from "react"
Enter fullscreen mode Exit fullscreen mode

Then initialize createContext:

const FoodContext = createContext()
Enter fullscreen mode Exit fullscreen mode

Finally, wrap the components you want to have access to the context in the Context Provider with the value of your state:

function App() {
    const [food, setFood] = useState({
        name: "Pho",
        cuisine: "Vietnamese",
        portion: 1
    })

    return (
        <FoodContext.Provider value={food}>
            <ChildComponent />
        </FoodContext.Provider>
    )
}
Enter fullscreen mode Exit fullscreen mode

Using Context

Now that you've created your Context, you'll need to use the useContext hook in your child component(s) to access it. Start by importing useContext:

import { useContext } from "react"
Enter fullscreen mode Exit fullscreen mode

Finally, you can use useContext throughout your child component(s)!

function ChildComponent() {
    const food = useContext(FoodContext)

    return (
        <h1>{My Favorite is: ${food.name}}</h1>
    )
}
Enter fullscreen mode Exit fullscreen mode

Updating State in Child Components

In addition to passing state as the value in your Context Provider, you can also include the setter function to update state from child components. For example:

<FoodContext.Provider value={{ food, setFood }}>
    <ChildComponent />
</FoodContext.Provider>
Enter fullscreen mode Exit fullscreen mode

Now, in your child component, you have access to the state and the setter function:

function ChildComponent() {
    const { food, setFood } = useContext(FoodContext)

    if (food.name === "Pho") {
        setFood((previousFood) => {
            return {
                ...previousFood,
                name: "Bánh mì"
            }
        })
    }

    return (
        <h1>{My Favorite is: ${food.name}}</h1>
    )
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

React Context allows your child components to easily access data from a parent. Depending on how deep your component hierarchy is, Context can be a simpler way to pass data through your component tree than passing data as props.

💖 💪 🙅 🚩
johnnyturco
Johnny Turco

Posted on January 9, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

custom fetch hook
react custom fetch hook

March 13, 2024

REACT HOOKS
beginners REACT HOOKS

January 18, 2024

React 80% : useState and useEffect
webdev React 80% : useState and useEffect

January 1, 2024

React Hooks - useEffect()
react React Hooks - useEffect()

July 21, 2023

Intro to React Context
react Intro to React Context

January 9, 2023