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

301
Views
Execute useEffect() only on specific setState()

I am using a hook component and several state variables. I have read about using useEffect() with params to get a kind of callback after updating a state. Example:

export const hookComponent = () => {
    const [var, setVar] = useState(null);
    useEffect(() => {
        //do things
    }, [var])
}

In this example, useEffect() would be executed on every setVar() call. In my case, I do not want to execute useEffect() everytime, but only on specific occasions. I would like to give the setVar() some kind of information which I can use in useEffect() like setVar(newValue, true).

Note: I do not want to store this information in var.

Is there a way to do this?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Like Nizar said, simple conditional check on 'var' in useEffect

If expensive calc you can

const expensiveValue = useMemo(() => {
    // other logic here if needed
    // could even be simple return var=='x'?true:false, although this would be easier to do in the useEffect hook?
    return computeExpensiveValue(var);
},[var]);

useEffect(() => {
    //do things
    //expensiveValue only changes when you want it to from the memo
}, [expensiveValue])
about 4 years ago · Juan Pablo Isaza Report

0

Thank you sambomartin and Nizar for your input.

For everyone looking for an answer: After some further research I found 3 possible solutions:

  1. Use a class component. If you really are dependent on that state update to be completed switch to a class component, which allows you to give the setState() a callback as a second param.
  2. Use the useRef hook to determine where your state update is comming from. You can use this information in the useEffect() method.
  3. Get independent from the state. I used this solution and externalized my callback function with the drawback of giving it every parameter on every call, although they are present in the component the states are saved.
about 4 years ago · Juan Pablo Isaza Report

0

As far as I know, the useEffect only triggers if the dependency value changes, not simply by executing setValue.

I offer you three solutions, the first one, close to what you want but without using useEffect hook, the second one is an extension of the first one, that may be required if you need control over the previous state, and the third, more general, like comments say, though it won't be triggered if the state is the same, even if you execute setValue.

  1. First solution: Wrap your set value with another function that definitely controls what may happen after or before the new state:
export default function MyComponent() {
  const [state, setState] = useState(null);

  const handleChangeSetState = (nextState, flag) => {
    if (flag) {
      specialUseCaseCb();
    }
    setState(nextState);
  };

  return <div>{/* ... */}</div>;
}
  1. Second solution: Wrap your set value with another function, like in the solution 1, and ask for the previous or next state within setState inner callback:
export default function MyComponent2() {
  const [state, setState] = useState(0);

  const handleChangeSetState = (increment, flag) =>
    setState((prevState) => {
      const nextState = prevState + increment;
      // you may need prevState or nextState for checking your use case
      if (flag) {
        specialUseCaseCb();
      }
      return nextState;
    });

  return <div>{/* ... */}</div>;
}
  1. Third solution: use useEffect hook to follow changes, remember though that setState won't re-trigger useEffect hook if the state is the same:
export default function MyComponent3() {
  const [state, setState] = useState("");

  // notice that this will only be triggered if state changes
  useEffect(() => {
    if (state !== "my-special-use-case") return;
    specialUseCaseCb();
  }, [state]);

  return <div>{/* ... */}</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!