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

Learn how to update props of a rendered component

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 (
      <span>Total Items: {totalItems}</span>
      <span data-testid="instance-id">{id.current}</span>

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


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

Hope you found this post useful. It was published . Please show your love and support by sharing this post.