1

React's useEffect looks like this:

useEffect(() => {
  effect
  return () => {
    cleanup
  }
}, [input])

where input is a list of values that trigger the effect when changed.

Let's say that I'm watching a number and I only want to trigger the effect when the number reaches 10. Is it possible to do that?

So far the best I could come up with is to encode the watched expression in a boolean value. The effect is then triggered twice, once when the boolean flips from false to true and a second time when it flips back to false. This is once too many.
Here's a small example:

export default function App() {
  const [num, setNum] = useState(0);
  const hit10 = num === 10;
  useEffect(() => {
    console.log("resetting");
    setNum(0);
  }, [hit10]);

  return (
    <button
      onClick={() => {
        setNum(num + 1);
      }}
    >
      {num}
    </button>
  );
}
Joshua
  • 3,055
  • 3
  • 22
  • 37
lhk
  • 27,458
  • 30
  • 122
  • 201

1 Answers1

2

You don't need to use another variable like hit10, You can just put a condition inside useEffect() hook to check the number's value every time that the component was rendered.

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

    export default function App() {
      const [num, setNum] = useState(0);

      useEffect(() => {
        if(num === 10) {
          console.log("resetting");
          setNum(0);
        }
      }, [num]);

      return (
        <button
          onClick={() => {
            setNum(num + 1);
          }}
        >
          {num}
        </button>
      );
    }
zb22
  • 3,126
  • 3
  • 19
  • 34