How to Program
How to Program

Reputation: 389

useeffect not running on first mount but runs after first reload

onStart is button and when i press it , it must run useeffect but it does not run it in first start but run it on reload. state value change on first start on dev tool.

const [started, setStarted] = useState(false);

const onStart = () => {
        setStarted(true);
      };

useEffect(() => {
    if(started){
    let timer = setInterval(() => tick(), 1000);
    return () =>  clearInterval(timer);
      }
  }, []);

Upvotes: 0

Views: 38

Answers (1)

Corey Larson
Corey Larson

Reputation: 1154

You need to add started to the dependency array of the useEffect.

const [started, setStarted] = useState(false);

const onStart = () => {
  setStarted(true);
};

useEffect(() => {
  if (started) {
    let timer = setInterval(() => tick(), 1000);
    return () =>  clearInterval(timer);
  }
}, [started]); // Add started here.

Upvotes: 2

Related Questions