reactjsreact-hooksdom-manipulation

Unable to understand re rendering behaviour


I am passing the parent state variable to child and updating its value in the child but the re rendering is not happening the way I expected.

In the below code, the child and parent both re render on the first button click but on the second button click only parent re renders and nothing happens on subsequent clicks.

import { useState } from "react";

const Footer = () => {
    const [sample, setSample]= useState("hello");
    console.log("parent")
  return (
    <>
        <Child sample={sample} setSample={setSample} />
    </>
  );
};

export default Footer;

const Child = ({sample,setSample}) => {
    console.log("child")
    return <div>  <h1>{sample}</h1>  <button onClick={()=>setSample("hi")}> Click me </button></div>
}
  1. Why the parent re renders on the second click when nothing has changed, also why child doesn't?
  2. Why the parent doesn't re render on the third click onwards like it did on second click ?

Solution

  • There seems to be nothing wrong here. Let's follow step by step:

    1. The initial state is "hello". Then you click and set it to "hi". (this was the first click.) Parent re-renders as the setState is called, and updates the state. Child also re-renders because the state is changed and i has a different value than before.
    2. You click the button a second time. This time the state is already "hi", and you are setting it to "hi" again. Therefore setState is called, parent re-renders because of the setState, but the state is not changed. So the Child Component doesn't re-render.

    React listens to state changes, if the prop value didnot change, re-render is not triggered.

    Edit: 3rd click doesnt re-render because React knows when you clicked the second time, nothing changed, so it stops re-rendering unless the state is updated with a new value.