How to trigger useEffect() hook at each setMyState() even if the new value equals the previous value?

Viewed 981

I am trying to implement a logic where I need to perform an action every time a component uses setMyState(value) (where I note the previous value of the state as preValue) using the useEffect() hook with myState as a dependency.

This works as I want when value !== prevValue. However, if value === prevValue, the hook doesn't trigger, which is logical in term of optimization. But what would be the correct way to still trigger the hook at each setMyState(value) call ? It may be a design flaw as I'm quite new to React.

Thank you in advance.

1 Answers

The useEffect only trigger when new value is different than previous value. But you can use this hack to trigger useEffect on every value change.

const [state, setState] = useState({ name: "" });

useEffect(() => {
  console.log("called... " + state.name);
}, [state]);

const onValueChange = (e) => {
  setState({ name: e.target.value });
};

return (
  <div className="App">
    <h1>Car</h1>
    <select name="cars" id="cars" onClick={onValueChange}>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
  </div>);

sandbox

Related