A few days ago, I was teaching a junior of mine memoization in react and I came up with a descriptive way to show how re-rendering works.
Let's create a component a counter component
const Counter = () => {
const [count, setCount] = React.useState(0)
const increment = () => setCount(count +1)
console.log("render from counter")
return (
<>
<h1> Counter: {count} </h1>
<button onClick={increment}>Add count</button>
</>
}
So basically, I have a counter component that will increment our count Everytime the button is clicked.
But also notice the console log there. Everytime I click on the button it will change the state which will make the component to re render, thus executing the console.log function.
Now we know that a component re renders whenever a state has changed, but it can also re render when it's props changes.
Let me show you what I mean.
const Counter = () => {
const [count, setCount] = React.useState(0)
const increment = () => setCount(count +1)
console.log("render from counter")
return (
<>
<h1> Counter: {count} </h1>
<button onClick={increment}>Add count</button>
<ChildCounter count={count} />
</>
}
// Child component
const ChildCounter = ({count}) => {
console.log("render from child")
return (
<>
<h1> our counter is now at : {count} </h1>
</>
}
Here I have another component that is a child of the counter component. And i am passing count as a prop to the child component.
Everytime the count changes in the parent component (ie. Counter), the child will re render.
That's because of two things. One is the props has changed and secondly is because the parent component will force its child to re render when it re renders.
Now you see that re rendering in react occurs when state has change, props change and parent change.
We can stop a child from unnecessary re renders using memorization which I won't be talking about here.
I hope this will help.
Excuse my lack of indentation and the ugly as* looking code in general.