Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading