calling rerender causes remounting
kasir-barati opened this issue · comments
@testing-library/react
version: 14.1.2- Testing Framework and version: jest, 29.7.0
- DOM Environment:
"jest-environment-jsdom": "^29.7.0"
Relevant code or config:
custom hook:
https://github.com/kasir-barati/my-nextjs-journey/blob/main/libs/hooks/use-update-effect.hook.ts
Test case:
What you did:
I was just making sure that my hook reset the useRef
on component unmount and not rerender (like when your states changes and react rerenders it), So I wrote the mentioned unit test to check that out.
What happened:
https://github.com/kasir-barati/my-nextjs-journey/blob/main/README.md#bug
Reproduction:
https://github.com/kasir-barati/my-nextjs-journey/
Problem description:
AFAIK rerender should not cause useEffect to call cleanup callback since it should be invoked only when the component is unmounted. But here it is not the case. I thought something is wrong with the testing library. But I am not 100% sure and also not does not have the confident to do that. So please feel free to enlighten me on what IDK. 🙏
Suggested solution:
Do not have any
Found some clues here: testing-library/react-hooks-testing-library#9
Correct me if I'm wrong or I didn't understand the issue correctly, but React calls the cleanup function on every re-render, that's React's behavior:
https://react.dev/reference/react/useEffect
So it looks like what you're experiencing is the default behavior, isn't it?
hmm, my bad. then I think I cannot test this scenario using react testing lib:
I was just making sure that my hook reset the useRef on component unmount and not rerender (like when your states changes and react rerenders it), So I wrote the mentioned unit test to check that out.
Or it is possible still?
AFAIU, there's no way to test this because it's not what happens. React will call your cleanup function but then call your setup again, so you might be able to count the times this happens.
Having said that, this is an extreme implementation detail, if react will change it's behavior in the future, this test will likely fail. I wouldn't go down that path and try to find a way to test this hook by ignoring it's implementation details.