Thursday, 22 June, 2023 UTC


Summary

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.
The post Adding useState() to React Context appeared first on Js Craft.