I am currently asking myself the following question: Is it recommended that I define my state and logic directly in the ContextProvider or is it okay if I define the state and logic in a separate function to separate the code a bit?
Example:
const MyContext = React.createContext({});
const createStore = () => {
const [myState, setMyState] = useState();
return {
myState,
setMyState
}
}
const MyContextProvider = ({ children }) => {
const store = createStore();
return (
<MyContext.Provider value={store}>{children}</MyContext.Provider>
)
}
I am a little bit affraid of that createStore function. Does the createStore always gets recreated if the Provider rerenders ?
Edit: Thanks for the answer!
What if I want to use a parameter in the useCreateStore hook ?
Will the parameter gets updated?
Example:
const MyContext = React.createContext({});
const useCustomStore= (myAwesomeValue) => {
const [myState, setMyState] = useState();
const doSomething = useCallback(() => {
//
}, [myAwesomeValue])
return {
myState,
setMyState
}
}
const MyContextProvider = ({ children, title }) => {
const { myState } = useCustomStore(title); //You need to desctructure the returned object here, note myState
return (
<MyContext.Provider value={myState}>{children}</MyContext.Provider>
)
}