Sobes.tech
Middle+

Write an abstract implementation of a Child component with memoization using React.memo. What is the second argument that React.memo accepts?

sobes.tech AI

Answer from AI

React.memo is a Higher Order Component (HOC) that memoizes a functional component, preventing it from re-rendering if the props haven't changed.

The second argument of React.memo is a comparison function (areEqual), which takes (prevProps, nextProps) and should return true if the props are considered equal (meaning no re-render needed), and false if the component should update.

Example of an abstract Child component with React.memo:

import React from 'react';

const Child = React.memo(function Child({ data }) {
  console.log('Child render');
  return <div>{data.text}</div>;
}, (prevProps, nextProps) => {
  // Compare only the text field
  return prevProps.data.text === nextProps.data.text;
});

export default Child;

In this example, the Child component will only re-render if the data.text field changes. If the props are equal according to the comparison function, React will skip re-rendering.

Write an abstract implementation of a Child component… - sobes.tech