Reputation: 43
I am going to use reacts context api plus reducers. Because I found many ways to implement this and a lack of documentation, I don't know if I am doing it right. In order to have a global state, I have done this:
import {createContext, useReducer} from "react";
import {appReducer} from "../reducers/appReducer";
function lazyInitializer() {
return {db: 1}
}
export const AppContext = createContext(); //Invalid number of arguments, expected 1 (defaultValue)
const AppContextProvider = (props) => {
const [globalState, appDispatch] = useReducer(appReducer, null, lazyInitializer);
return (
<AppContext.Provider value={{globalState, appDispatch}}>
{props.children}
</AppContext.Provider>
)
}
export default AppContextProvider;
Do I have to supply a default value to createContext
? Is this the right way to use lazy initializers? It does work how it is above. If there is a better solution realizing a global state please tell me.
Btw, I don't wanna use Redux in order to keep the project simple.
Upvotes: 2
Views: 1435
Reputation: 1
You can add a null
default value to remove the Invalid number of arguments exception.
Upvotes: -1