šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Adding useState() to React Context

It is very common to have setState() variables passed to the value in a React context.

Given that setState() is available only within React components I've seen cases where the value property of the main app context is initialized in the root of the app:

// ā›”ļø context value init in root component
import Context from 'Context'
const App = () => {
    const [ctxValue, setCtxValue] = useState(0)
    return (
        <Context.Provider value={{ctxValue, setCtxValue}} >
            <SomeComponent />
        </Context.Provider>
    );
}

A nicer approach is to build our own AppContextProvider component and use the children API to pass in the needed subcomponents.

And given that the provider of a React context is an actual component, we can use the useState() hook directly from within this AppContextProvider.

Something like this:

// āœ… packaged context

// AppContextProvider.js
export const AppContext = createContext({})
export default const AppContextProvider = ({children}) => {
    const [ctxValue, setCtxValue] = useState(0)
    return (<AppContext.Provider value={{ctxValue, setCtxValue}}>
        {children}
    </AppContext.Provider>)
}

// SomeComponent.js
import {AppContext} from 'AppContextProvider'
const SomeComponent = ()=> {
    const {ctxValue, setCtxValue} = useContext(AppContext)
    return <div>
        <p>The context value: {ctxValue}</p>
        <button onClick={() => setCtxValue(v => v +1) }>
            Increment myValue
        </button>
    </div>
}

// App.js
import AppContextProvider from  'AppContextProvider'
const App = () => {
    return (
        <AppContextProvider>
            <SomeComponent />
        </AppContextProvider>
    );
}

You can browse the code for this example here and see the running app on GitHub pages.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *