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>
}
There seems to be nothing wrong here. Let's follow step by step:
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.