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.
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js