Skip to content

Commit

Permalink
Support ref unmounting on imperative handles (#4625)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock authored Jan 8, 2025
1 parent a1ff5f3 commit 1226aae
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
7 changes: 5 additions & 2 deletions hooks/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -320,8 +320,11 @@ export function useImperativeHandle(ref, createHandle, args) {
useLayoutEffect(
() => {
if (typeof ref == 'function') {
ref(createHandle());
return () => ref(null);
const result = ref(createHandle());
return () => {
ref(null);
if (result && typeof result == 'function') result();
};
} else if (ref) {
ref.current = createHandle();
return () => (ref.current = null);
Expand Down
24 changes: 24 additions & 0 deletions hooks/test/browser/useImperativeHandle.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,30 @@ describe('useImperativeHandle', () => {
expect(ref.current.test()).to.equal('test');
});

it('Calls ref unmounting function', () => {
let ref;
const unmount = sinon.spy();

function Comp() {
useImperativeHandle(
r => {
ref = r;
return unmount;
},
() => ({ test: () => 'test' }),
[]
);
return <p>Test</p>;
}

render(<Comp />, scratch);
expect(ref).to.have.property('test');
expect(ref.test()).to.equal('test');
render(null, scratch);
expect(unmount).to.be.calledOnce;
expect(ref).to.equal(null);
});

it('calls createHandle after every render by default', () => {
let ref,
createHandleSpy = sinon.spy();
Expand Down

0 comments on commit 1226aae

Please sign in to comment.