Home > front end >  Does React know not to re-render child when parent changes?
Does React know not to re-render child when parent changes?

Time:01-27

<Parent P={some_state} >
  <Child />
<Parent />

If some_state changes, causing the Parent to re-render, does it know to leave Child alone?

CodePudding user response:

React Memo

I think what you are looking for is React.memo. Memoizing a component tells the component not to change or render unless the props it cares about changes or it has it's own internal changes.

In your example, if someState changes in the <Parent /> the <Child /> will render again. To fix that we can memoize our child.

Example Implementation

// Child Component
import React, { useEffect } from "react";
const Child = () => {
 useEffect(() => console.log("Child rendered")); // simple way of logging each time the component renders

  return ( 
    <span>
      I take no props, I shouldn't update unless my local state changes
    </span>
  )
};

const MemomizedChild = React.memo(Child);

// Parent Component
const Parent = ({ someState }) => { 
 return (
   <MemomizedChild />
 )
};

// Parent of Parent Component
import { useEffect, useState } from "react";
const App = () => { 
  const [foobar, setFoobar] = useState("hello");
  
   useEffect(() => {
    setTimeout(() => setFoobar("world"), 5000)
   }, []) // after 5 seconds change the state variable to "world"

   return (
     <Parent someState={foobar} />
   )
}

Explanation

Here are the steps or chain of events in that example:

  • App component has a local state variable foobar (just to trigger a prop change in the Parent component)
  • After five seconds the Parent's someState will change
    • Normally would trigger a render from the Child
  • We memoized Child so we should only see that "Child rendered" console log once

If we use the non memoized Child component the "Child rendered" console log will fire twice, once on mount and the second time when the Parent props change.

  •  Tags:  
  • Related