Skip to content

Commit

Permalink
Merge branch 'master' into fix/preactjs#2644
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin Oppitz authored Jul 28, 2020
2 parents a507b84 + 8096765 commit 9b6fda2
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion hooks/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ type Ref<T> = { current: T };
* Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable
* value around similar to how you’d use instance fields in classes.
*/
export function useRef<T>(initialValue: T | null): Ref<T>;
export function useRef<T>(initialValue?: T | null): Ref<T>;

/**
* `useRef` without an initial value is the special case handling `ref` props.
Expand Down
5 changes: 4 additions & 1 deletion hooks/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ export function useLayoutEffect(callback, args) {

export function useRef(initialValue) {
currentHook = 5;
return useMemo(() => ({ current: initialValue }), []);
return useMemo(
() => ({ current: initialValue === undefined ? null : initialValue }),
[]
);
}

/**
Expand Down
16 changes: 16 additions & 0 deletions hooks/test/browser/useRef.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,20 @@ describe('useRef', () => {

expect(values).to.deep.equal([1, 2]);
});

it('defaults to null', () => {
const values = [];

function Comp() {
const ref = useRef();
values.push(ref.current);
ref.current = 2;
return null;
}

render(<Comp />, scratch);
render(<Comp />, scratch);

expect(values).to.deep.equal([null, 2]);
});
});

0 comments on commit 9b6fda2

Please sign in to comment.