Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: replace useState with useReducer #5

Merged
merged 2 commits into from
Feb 28, 2019
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
23 changes: 8 additions & 15 deletions src/use-force-update.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
import { useState } from 'react';
import { useReducer } from 'react';

interface VoidFunction {
(): void;
}
type VoidFunction = () => void;
type VoidFunctionCreator = () => VoidFunction;
type ToggleReducer = (state: boolean, action: void) => boolean;

interface VoidFunctionCreator {
(): VoidFunction;
}
const reducer: ToggleReducer = state => !state;

const toggle = (state: boolean): boolean => !state;

const useForceUpdate: VoidFunctionCreator = (): VoidFunction => {
const [ , setState ] = useState<boolean>(true);
const forceUpdate: VoidFunction = (): void => {
setState(toggle);
};
return forceUpdate;
const useForceUpdate: VoidFunctionCreator = () => {
const [, dispatch] = useReducer(reducer, true);
return dispatch as VoidFunction;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will wait on feedback regarding the as VoidFunction, maybe there's a way around it.

no hurries to merge, it's not even a direct dependency of mine :P
I stumbled upon it while reading your use-react-router.

};

export default useForceUpdate;
6 changes: 6 additions & 0 deletions tests/use-force-update.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,10 @@ describe('useForceUpdate', () => {
expect(renders).to.equal(2);
});

it('update function should return undefined', () => {
expect(forceUpdate()).to.be.undefined;
// @ts-ignore test with parameters :shrug:
expect(forceUpdate('anything')).to.be.undefined;
});

});