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

84
Visualizações
React hook not triggering re-render with boolean state

I have a custom hook with a useState holding a boolean value and function that allows me to update the state, I was expecting react to trigger a re render based on the new value but nothing happens

import React, { useState, useEffect } from 'react';

function useHook() {
  const [value, setValue] = useState(false);

  const onClick = (v) => {
    setValue(v);
  };

  return {value, onClick};
}

const Switcher = () => {
  const {value, onClick} = useHook();
  return <button onClick={() => onClick(!value)}>test</button>;
};

export default function App() {
  const {value} = useHook();

  useEffect(() => {
    console.log('effect', value);
  }, [value]);

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>result {JSON.stringify(value)}</p>
      <Switcher />
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Hooks are ways to reuse behavior, not state. In other words, you’re creating 2 value states when you call useHook in App and Switcher, respectively. If you want to reuse state without just passing it via props, you’ll need to use something like redux or the Context API.

about 4 years ago · Juan Pablo Isaza Relatório

0

You have two separate calls to useHook which creates to separate states. What you want is one state that gets used in both components. Try passing value and onClick as props into Switcher from the parent component like so:

import React, { useState, useEffect } from 'react';

function useHook() {
  const [value, setValue] = useState(false);

  const onClick = (v) => {
    setValue(v);
  };

  return {value, onClick};
}

const Switcher = ({onClick, value}) => {
  return <button onClick={() => onClick(!value)}>test</button>;
};

export default function App() {
  const {value, onClick} = useHook();

  useEffect(() => {
    console.log('effect', value);
  }, [value]);

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>result {JSON.stringify(value)}</p>
      <Switcher onClick={onClick} value={value}/>
    </div>
  );
}
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