StrangeLoop
StrangeLoop

Reputation: 531

useRef hook not triggering re-render

For some reason my test is not passing when using ref like this:

import React, { useRef } from "react";
import { waitForElement, render } from "@testing-library/react";

const MyComponent = props => {
  const elementRef = useRef(null);
  return (
    <div>
      <div ref={elementRef} />
      {elementRef.current && <div data-testid="test-div" />}
    </div>
  );
};

describe("MyComponent", () => {
  it("test-div should exist when the ref is set", async done => {
    const { getByTestId } = render(<MyComponent />);
    await waitForElement(() => getByTestId("test-div"));
  });
});

Any idea why this is not working?

Upvotes: 12

Views: 32488

Answers (1)

Mikaela
Mikaela

Reputation: 536

It's not the test that is not working, it's the rendering of the "test-div". If you tried rendering this component outside of the test, you would get the same result. As stated in the React Documentation:

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

This means that even though the ref gets set, the re-render never happens. You would need to trigger it through other means, perhaps by using a callback ref as stated above.

Upvotes: 21

Related Questions