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

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

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 Denunciar

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 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