3

I have parent component with multiple child components. Different types of data will be passed to child components after getting data from api. Some of the components will get object as a prop. I am trying to avoid rerenders in that component. Even if the data is same it is rerendering. How can i avoid this rerenders?

const Parent = () => {
  const [childData, setChildData] = useState(null);
  
  useEffect(() => {
    const data = getChildData();
    setChildData(data);
  }, [])

  return (
      <Child data={childData}/>
  );
};

const Child = React.memo((props) => {
  const {name, email} = props.data;
  return (
      <div>
        <p>Name: {name}</p>
        <p>Email: {email}</p>
      </div>
  );
});
Sudeep Kumar
  • 839
  • 1
  • 7
  • 16

2 Answers2

7

As per React Official Docs, By default React will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument. https://reactjs.org/docs/react-api.html#reactmemo. Here is an example.

const Parent = () => {
    const [childData, setChildData] = useState(null);

    useEffect(() => {
        const data = getChildData();
        setChildData(data);
    }, [])

    return (
        <Child data={childData} />
    );
};

function areEqual(prevProps, nextProps) {
    return prevProps.name == nextProps.name && prevProps.email == nextProps.email;
}
const Child = React.memo((props) => {
    const { name, email } = props.data;
    return (
        <div>
            <p>Name: {name}</p>
            <p>Email: {email}</p>
        </div>
    );
}, areEqual);

rex
  • 359
  • 1
  • 5
2

By default React.memo will only shallowly compare complex objects in the props.

You can use custom equality check of props. Pass the custom check function as second argument to React.memo similar to below

const areEqual = (prevProps, nextProps) => {
  const {name, email} = prevProps.data;
  const {name: nextName, email: nextEmail} = nextProps.data;
  return name === nextName && email === nextEmail;
};

const Child = React.memo((props) => {...}, areEqual);

For more details check here.

Prathap Reddy
  • 1,688
  • 2
  • 6
  • 18