I'm trying to set loginFlag in the state throughout the application. I'm using useReducer hook to perform that action. It looks like the state is limited to the page A where I dispatched the action. When I go to page B, I'm seeing the initial state.
Excerpt from my code
Component A
const Home = () => {
const [state, dispatch] = useReducer(reducer, initialState);
console.log("state in home", state);
return (
<div>
<button onClick={() => dispatch({ type: "count" })}>Count</button>
</div>
);
};
Component B
const About = () => {
const [state, dispatch] = useReducer(reducer, initialState);
console.log("state in about", state);
return (
<div>
About page
</div>
);
};
I created a working example using CodeSandbox. Could anyone please help?
That's because you are creating two different stateful variables that happen to both be named 'state'.
If you create the state in the App component, and pass it down as a prop to both the Home and About components, it will work.
See this codesandbox example. It also renders both components as children for the / route (recommended in Router docs) so it console logs the state of both.