Skip to content

Commit

Permalink
Improvement for useBoolean hook (#15607)
Browse files Browse the repository at this point in the history
  • Loading branch information
FuJuntao authored Oct 21, 2020
1 parent 5dcd2ab commit bf6bf4c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
8 changes: 8 additions & 0 deletions change/@uifabric-react-hooks-2020-10-22-01-00-51-master.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"type": "patch",
"comment": "Improvement for `useBoolean` hook",
"packageName": "@uifabric/react-hooks",
"email": "fu.juntao358@gmail.com",
"dependentChangeType": "patch",
"date": "2020-10-21T17:00:51.102Z"
}
9 changes: 3 additions & 6 deletions packages/react-hooks/src/useBoolean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,16 @@ export interface IUseBooleanCallbacks {
*/
export function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks] {
const [value, setValue] = React.useState(initialState);
// Storing the value in a ref is redundant but allows the `toggle` callback to have a
// constant identity, which overall is probably better for consumers' perf.
const valueRef = React.useRef(value);

const setTrue = useConst(() => () => {
setValue(true);
valueRef.current = true;
});
const setFalse = useConst(() => () => {
setValue(false);
valueRef.current = false;
});
const toggle = useConst(() => () => (valueRef.current ? setFalse() : setTrue()));
const toggle = useConst(() => () => {
setValue(currentValue => !currentValue);
});

return [value, { setTrue, setFalse, toggle }];
}

0 comments on commit bf6bf4c

Please sign in to comment.