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

80
Views
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 answers
Answer question

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 Report

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