skip to Main Content

If I have a component say- <Component />
which acceps props as data={a:1, b:2} which is created after some custom operation lets say that operation is performed by a function getData() which returns this data object.

Now this component re-renders and again getData returns us data={a:1, b:2} as props.

Now will my <Component /> update on UI? as the memory location of both the props is different but their properties are same?

3

Answers


  1. For props React uses shallow comparison. Which just like you wrote means that for objects, it’s determined by if the object memory reference is the same.
    Here is an article about it more in detail.

    So in your case, where getData returns a new reference, the child component would re-render even though it has the same fields and values.

    Login or Signup to reply.
  2. You could use useMemo hook to avoid re-rendering issue.

    const getData = () => {
      return { a: 1, b: 2 };
    };
    
    const MyComponent = React.memo(({ data }) => {
      console.log("Component re-rendered");
      return (
        <div>
          <p>a: {data.a}</p>
          <p>b: {data.b}</p>
        </div>
      );
    });
    
    const App = () => {
      const data = useMemo(() => getData(), []);
    
      return <MyComponent data={data} />;
    };
    Login or Signup to reply.
  3. By default, React will re-render your component because the dataprop’s reference changes even if the values are the same but you can use React.memo with a custom comparison function.

    import React from 'react';
    
    const Component = React.memo(({ data }) => {
      
      return <div>{data.a}, {data.b}</div>;
    }, (prevProps, nextProps) => {
      
      return prevProps.data.a === nextProps.data.a && prevProps.data.b === nextProps.data.b;
    });
    

    React.memo will prevent re-rendering of Component unless the values of a or b in the data object change.

    function ParentComponent() {
      const data = getData();
      return <Component data={data} />;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search