jslover69
jslover69

Reputation: 11

why does the component render 3 times?

I have a component like this:

import { useEffect, useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  console.log("comp run");

  const tick = () => {
    setCount(count + 1);
    console.log(count);
  };

  useEffect(() => {
    const timer = setInterval(tick, 10000);
    console.log("effect run");

    return () => {
      clearInterval(timer);
      console.log("clear func run");
    };
  }, []);

  return <div>{count}</div>;
}

export default Counter;

When the code runs, the console outputs as follows:

Output immediately when the program runs:


comp run

effect run


after 10 seconds :


comp run

0


after 10 seconds :


comp run

0


after 10 seconds :


0 (then it keeps increasing by 0 every ten seconds)


What I don't understand here is exactly this: "comp run" is printed on the screen 3 times. Why 3 ?

Upvotes: 1

Views: 500

Answers (1)

Anton Neverov
Anton Neverov

Reputation: 311

This is because useEffect memoize all values inside it. You can use two ways:

  1. Add count to useEffect's dependencies array. And when count changes, useEffect will refreshed.

    useEffect(() => {
        //Your old code here
    }, [count]); //Here
    
  1. Create a function inside of useCallback hook and memoize function for better performance. Works like in first way, but dependent by tick fucntion, wich dependent by count state.

    const tick = useCallback(() => {
      setCount(count + 1);
      console.log(count);
    }, [count]);
    
    useEffect(() => {
      const timer = setInterval(tick, 1000);
      console.log("effect run");
    
      return () => {
        clearInterval(timer);
        console.log("clear func run");
      };
    }, [tick]);
    

Upvotes: 1

Related Questions