We are going to use Hooks Api to create global store.
First Create Basic Store that can be passed through components.
import { createContext, useContext } from "react";
const Store = createContext();
export const useStore = () => useContext(Store);
Now create a reducer to update the state and we are going to useReducer Hook
const reducer = (state, action) => {
console.log(action);
switch(action.type){
......
......
default:
{
return state;
}
}
}
Now create a Store Provider method
export const StoreProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, {});
return (
<Store.Provider value={[state, dispatch]}>
{children}
</Store.Provider>
);
}
Now you can simply import this StoreProvider in your App Component and Wrap it
import { StoreProvider } from "path/to/store/provider";
function MyApp({ Component, pageProps }) {
return (
<StoreProvider>
<Component {...pageProps} />
</StoreProvider>
);
}
export default MyApp
Now if you want to use state and dispatch actions use useStore method in your children component like this
const [state, dispatch] = useStore();