Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda