How to Update the Props of a Rendered Component in React Testing Library?

If you wish to update the props of a rendered component in your React testing library test, then you can simply use the rerender function like so:

import { render } from '@testing-library/react';

const { rerender } = render(<MyComponent prop="foo" />);

// re-render the same component with different props
rerender(<MyComponent prop="bar" />);

In this way, you won't be remounting the component. To demonstrate this, consider the following example:

import React, { useRef } from 'react';
import { render, screen } from '@testing-library/react';

let idCounter = 1;

const Wishlist = ({ totalItems }) => {
  const id = useRef(idCounter++);

  return (
    <div>
      <span>Total Items: {totalItems}</span>
      <span data-testid="instance-id">{id.current}</span>
    </div>
  );
};

test('re-rendering the same component with different props does not remount', () => {
  const { rerender } = render(<Wishlist totalItems={1} />);
  expect(screen.getByText('Total Items: 1')).toBeInTheDocument();

  rerender(<Wishlist totalItems={2} />);
  expect(screen.getByText('Total Items: 2')).toBeInTheDocument();

  expect(screen.getByTestId('instance-id')).toHaveTextContent('1');
});

As you can see in the example above, the "instance-id" remains the same after re-rendering. This proves that the rendered component does not remount when using the rerender function (i.e. a new instance of the rendered component is not created).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.