useRef hook not triggering re-render

11,987

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 or creating a useEffect hook that reacts to the current value of the ref.

Share:
11,987
StrangeLoop
Author by

StrangeLoop

Updated on June 21, 2022

Comments

  • StrangeLoop
    StrangeLoop almost 2 years

    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?