Skip to content
Advertisement

How to avoid re-rendering when i pass an object as prop to child component?

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>
  );
});

Advertisement

Answer

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);

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement