Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
useReducer shows initial state in different component in React

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!