Skip to content

Commit

Permalink
reset useImperativeHandle ref to null when the component get unmounted (
Browse files Browse the repository at this point in the history
#3487)

Co-authored-by: Jovi De Croock <decroockjovi@gmail.com>
  • Loading branch information
deadem and JoviDeCroock committed Mar 26, 2022
1 parent 2232f40 commit 75c4032
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
9 changes: 7 additions & 2 deletions hooks/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,13 @@ export function useImperativeHandle(ref, createHandle, args) {
currentHook = 6;
useLayoutEffect(
() => {
if (typeof ref == 'function') ref(createHandle());
else if (ref) ref.current = createHandle();
if (typeof ref == 'function') {
ref(createHandle());
return () => ref(null);
} else if (ref) {
ref.current = createHandle();
return () => ref.current = null;
}
},
args == null ? args : args.concat(ref)
);
Expand Down
19 changes: 19 additions & 0 deletions hooks/test/browser/useImperativeHandle.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,23 @@ describe('useImperativeHandle', () => {

expect(() => render(<Comp />, scratch)).to.not.throw();
});

it('should reset ref to null when the component get unmounted', () => {
let ref,
createHandleSpy = sinon.spy(() => ({ test: () => 'test' }));

function Comp() {
ref = useRef({});
useImperativeHandle(ref, createHandleSpy, [1]);
return <p>Test</p>;
}

render(<Comp />, scratch);
expect(createHandleSpy).to.have.been.calledOnce;
expect(ref.current).to.not.equal(null);

render(<div />, scratch);
expect(createHandleSpy).to.have.been.calledOnce;
expect(ref.current).to.equal(null);
});
});

0 comments on commit 75c4032

Please sign in to comment.