Skip to content Skip to sidebar Skip to footer

React - Functions As Props Causing Extra Renders

I have some heavy forms that I'm dealing with. Thus, I'm trying to squeeze performance wherever I can find it. Recently I added the Why-did-you-render addon to get more insight on

Solution 1:

The problem stems from the way you define your change handlers:

constupdateName = (_v) => updateState('name', _v)

This line is called on each render and thus, every time your component is rendered, the prop has a new (albeit functionality-wise identical) value. The same holds for every other handler as well.

As an easy solution you can either upgrade your functional component to a fully fledged component and cache the handlers outside of the render function, or you can implement shouldComponentUpdate() in your child components.

Solution 2:

You need to use memo for your child components to reduce renders

constSomeInputComponent  = props => {

};

exportdefaultmemo(SomeInputComponent);

// if it still causes rerender witout any prop change then you can use callback to allow or block render

e.f.

functionarePropsEqual(prevProps, nextProps) {
  return prevProps.name === nextProps.name; // use your logic to determine if props are same or not
}

exportdefaultmemo(SomeInputComponent, arePropsEqual);

/* One reason for re-render is that `onChange` callback passed to child components is new on each parent render which causes child components to re-render even if you use `momo` because function is updated on each render so in order to fix this, you can use React hook `useCallback` to get the same function reference on each render.


So in you parent component, you need to do something like 
*/import { useCallback } from'react';


const updateName = useCallback((_v) =>updateState('name', _v), [])

Solution 3:

You have to memoize parent function before pass to children, using useCallback for functional component or converting to class property if you use class.

exportdefaultclassParentextendsReact.PureComponent {
    constructor(props) {
       super(props);
       this.onClick = this.onClick.bind(this);
    }

    onClick() {
       console.log("click");
    }

    render() {
        return (
           <ChildComponentonClick={this.onClick }
           />
        );
    }
}

with useCallback:

Parent = () => {
   const onClick = useCallback(
      () =>console.log('click'),
      [] 
   );

   return (
        <ChildComponentonClick={onClick}
        />
   );
}

Post a Comment for "React - Functions As Props Causing Extra Renders"