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 *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X