Home > Back-end >  Stop re-rendering using Callback hooks in react
Stop re-rendering using Callback hooks in react

Time:10-22

How can I stop Component B to render when I am doing changes in Component A only.

Example: Console.log("A") belongs to Component A while console.log("B") belongs to Component B. Now when I am updating a text in Component, I believe Component A is only called, hence printing A on the console.

However this is not the behavior. In my case both components are invoked, hence both consoles are logged.

What I want: Only the calling component should be invoked for an update...

A.tsx

retrun(
  <Details_A setter={setter} dataold={dataold}/>
  <Details_B setterOne={setterOne} datanew={datanew}/>
)

this is diffrent project which will be integrated to the parent project

Details_A.tsx


  console.log("A");
  return (
    <>
       hello world. I am in A now
      </>
  );
};

CodePudding user response:

By default, all children will be re-rendered when we update the state in the parent, there are a few ways to prevent this:

  1. If possible you can just move states updates to children directly, that way the parent will not be re-rendered and affect all children
  2. You can wrap children in memo function (which will prevent the re-render of a child if props are not changed), or use PureComponent, or base component with the custom shouldComponentUpdate

memo example:

import React, { memo } from 'react'
...
export const Details_A = memo(({ wrapper, details }) => {
  ...
  return <Something />
})
  • Related