reactjsrendering

How to check if a compnent is re-rendered or not in React?


I've been working with React for nearly 3 years, but sometimes run into difficulties in "Rendering" meaning.

Practically, to check "Rendering" I just put

console.log('render')

In a component right before

return <>...</>

Is this correct check? Or Can't I know whether it's re-rendered or not?


Solution

  • short answer

    The simplest way is to make a useEffect hook without a dependency array and log a message inside it.

    useEffect(() => {
      console.log("component rerendered");
    });
    

    component rerender

    You can declare a variable outside of the component and and initialize it to 0 and then increment it from inside the component:

    let count = 0;
    const Component = () => {
    count++;
    console.log("component render number: ", count);
    //...
    }
    

    this trick will let you see the logs

    component render number: n
    

    each time the function is invoked, because the component is a function after all, but the component might be only invoked without rerendering, therefore what you are doing is not the correct way to check.


    To understand that we can try this simple code without strict mode:

    let count = 0;
    const Component = () => {
    
    count ++;
    console.log("component render number: ", count);
    
    const [test, setTest] = useState(0);
    
    return (
      <>
        <button
          onClick={() => {
            setTest(1);
          }}
        >
          click me
        </button>
      </>
    );
    

    here we will see first

    component render number: 1
    

    we also know that the component rerenders only when the state takes a different value so when we click the button the first time we expect to see

    component render number: 2
    

    because the state value passes from 0 to 1, and this happens.

    Now when we click the button again, we don't expect to see

    component render number: 3
    

    because the state takes the same exact value so the component does not have to rerender, however we see the logs anyway.

    why this is happening?

    In fact in this case the component didn't rerendered, but only invoked

    If you return the same value from a Reducer Hook as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

    But we want to see logs only when the component rerenders, the simplest way is to make a useEffect hook without a dependency array, this will make it run after each component render:

    useEffect(() => {
      console.log("component rerendered");
    });
    

    Now when we click the button the second time we see only

    component render number: 3
    

    and no

    component rerendered