React Component keeps on Rendering

Asked
Active3 hr before
Viewed126 times

9 Answers

componentreact
90%

You can minimize your component's rerender by implementing a check inside your shouldComponentUpdate and returning false if it doesn't need to.,Here are some instances that a React component will re-render.,Parent component rerender

If you want a short snippet without any external dependencies I find this useful

componentDidUpdate(prevProps, prevState) {
   Object.entries(this.props).forEach(([key, val]) =>
      prevProps[key] !== val && console.log(`Prop '${key}' changed`)
   );
   if (this.state) {
      Object.entries(this.state).forEach(([key, val]) =>
         prevState[key] !== val && console.log(`State '${key}' changed`)
      );
   }
}

Here is a small hook I use to trace updates to function components

function useTraceUpdate(props) {
  const prev = useRef(props);
  useEffect(() => {
    const changedProps = Object.entries(props).reduce((ps, [k, v]) => {
      if (prev.current[k] !== v) {
        ps[k] = [prev.current[k], v];
      }
      return ps;
    }, {});
    if (Object.keys(changedProps).length > 0) {
      console.log('Changed props:', changedProps);
    }
    prev.current = props;
  });
}

// Usage
function MyComponent(props) {
  useTraceUpdate(props);
  return <div>{props.children}</div>;
}
load more v
88%

What causes a render in React?,A rendering in React is caused by ,React is extremely careful and re-renders “everything all the same time”. Losing information by not rendering after a state change could be very dramatic this is why re-rendering is the safer alternative.

class Parent extends React.Component {
  render() {
    console.warn('RENDERED -> Parent');
    return (
      <div>
        <Child />
        <Child name={name} />
      </div>
    );
  }
}
load more v
72%

React computes the differences between the current UI and the new UI by applying a comparison algorithm on the two versions of its virtual DOM.,While interacting with the app, updates are highlighted on the screen with colored borders. By this process, you should see components that have re-rendered. This lets us spot re-renders that were not necessary.,Each React application begins with a root component. We can think of the whole application as a tree formation where every node is a component. Components in React are ‘functions’ that render the UI based on the data. That means props and state it receives; say that is CF

Pretag
 Pretag team - issue, fix, solve, resolve
65%

If you are like me and prefer the functional paradigm of React then use the memo wrapper to protect functional components from re-rendering given the same input.,Passing anonymous functions as props will cause the receiving component to re-render every time its parent re-renders because anonymous functions are re-initialized on every state or props change. Even if the function is still the same it will create a new memory reference since the function has to be re-allocated. Try lifting inline functions one level up from render if possible. Alternatively use the callback wrapper for the anonymous function.,When a Context Provider re-renders, all of the child components in the tree are also being re-rendered. Even if a component is not consuming props from the context provider. Again, using the memo API can prevent the re-renders.

Passing anonymous functions as props will cause the receiving component to re-render every time its parent re-renders because anonymous functions are re-initialized on every state or props change. Even if the function is still the same it will create a new memory reference since the function has to be re-allocated. Try lifting inline functions one level up from render if possible. Alternatively use the callback wrapper for the anonymous function.

class App extends React.Component {  nameHandler = () => "foo"  render() {    <Incorrect name={() => "foo"} />    <Correct name={this.nameHandler} />  }}
load more v
75%

When a parent component renders, React recursively renders all of its child components. Let’s have a look at an example using the useState hook.,This involves handling callback functions props. In such cases, use extra caution when memoizing components that use props as callbacks as they may give different results on each render. For instance:,In an attempt to get away from the usual ‘counter’ and ‘timer’ naming conventions, this example of a buzzer has Loud and Soft components. The Loud component is the parent of Soft.

Pretag
 Pretag team - issue, fix, solve, resolve
40%

React shouldComponentUpdate is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed.,This is because the React app component got re-rendered after the state values were modified, and it also re-rendered its child components.,Once it detects something has changed, it will, by default, re-render the entire React component and it’s child components.

componentDidMount() {
  this.setState({ ruinPerformance: true });
}

render() {
  return (
    <SubComp>
      <SubComp>
        <SubComp>
          <SubComp>
            Hello world :)
          </SubComp>
        </SubComp>
      </SubComp>
      <SiblingComp />
    </SubComp>
  );
}
load more v
22%

How to optimize re-renders,Force a React component to rerender,Force a React component to rerenderUsing React's forceUpdate functionForce an update in React hooks

const App = () => {
  const [message, setMessage] = React.useState('');
  return (
    <>
      <Tile message={message} />
      <Tile />
    </>
  );
};
load more v
60%

Common reasons for rerendering: ,After you end the Profiler session, you’ll be able to drill down into individual components to see their render metrics. Under the “Why did this render?” heading you’ll see a list of reasons the component rendered/rerendered. ,a component’s parent rerendering

const memoizedComponent = React.memo(MyComponent,
   (prevProps, nextProps) => {

      console.log(prevProps.thing === nextProps.thing);

      /*
        When using this function you always need to return
        a Boolean. For now we'll say the props are NOT equal 
        which means the component should rerender.
      */
      return false;
   }
)
load more v
48%

Delete the remaining empty function declaration.,Replace props with this.props in the render() body.,Move the body of the function into the render() method.

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(    element,    document.getElementById('root')  );}

setInterval(tick, 1000);
load more v

Other "component-react" queries related to "React Component keeps on Rendering"