Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda