A Simple Hook for React Context
2 min read

A React Context Hook

Whenever I set up a new React project, I tend to use Context to pass around the state in the application. I often use this custom hook as a base. Here I arbitrarily name it GlobalContext.

import { createContext, useContext } from "react";

export interface GlobalContextInterface {
    numbers: number[]
}

const GlobalContext = createContext<GlobalContextInterface>({
    numbers: []
});

const useGlobalContext = () => useContext(GlobalContext);

export { GlobalContext, useGlobalContext };

This makes it quite easy both to set it up, as well as import it within components.

import { GlobalContext } from "./hooks/useGlobalContext";


const App = () => {

    return (
        <div>
            <GlobalContext.Provider value={{numbers: [1,2,3]}}>
                <RestOfApp />
            <GlobalContext.provider>
        </div>
    )
}

And whenever you want to import the state to a component, you use the provided hook.

import { useGlobalContext } from "./hooks/useGlobalContext";


const ChildComponent = () => {
    const { numbers } =
        useGlobalContext();

    //...
}