Skip to content

Commit

Permalink
feat: make stateful hooks use useSafeState
Browse files Browse the repository at this point in the history
  • Loading branch information
xobotyi committed May 2, 2021
1 parent 021d02a commit d181c7f
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ first.
- In case hook has some custom types as arguments or return values - it should also be exported.
- All types and interfaces should be `I` prefixed.
- Hook should be developed with SSR in mind.
- In case hook is stateful and exposes `setState` method it should use `useSafeState` instead of
`useState`, since `useSafeState`.
2. Reexport hook implementation and all custom types in `src/index.ts`.
3. Write complete tests for your hook, tests should consist of both DOM and SSR parts.
- Hook's test should be placed in `tests` folder and named after the hook.
Expand Down
6 changes: 4 additions & 2 deletions src/useRerender.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { useCallback, useState } from 'react';
import { useCallback } from 'react';
import { useSafeState } from './useSafeState';

const stateChanger = (state) => !state;

/**
* Return callback function that re-renders component.
*/
export function useRerender(): () => void {
const [, setState] = useState(false);
const [, setState] = useSafeState(false);

return useCallback(() => {
setState(stateChanger);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}
8 changes: 5 additions & 3 deletions src/useToggle.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useCallback, useState } from 'react';
import { useCallback } from 'react';
import { IInitialState, INewState, resolveHookState } from './util/resolveHookState';
import { useSafeState } from './useSafeState';

/**
* Like `useState`, but can only become `true` or `false`.
* Like `useSafeState`, but can only become `true` or `false`.
*
* State setter, in case called without arguments, will change the state to opposite.
*
Expand All @@ -15,7 +16,7 @@ export function useToggle(
// action does not provide functional updates feature.
// Therefore we have to create and expose our own state setter with
// toggle logic.
const [state, _setState] = useState(initialState);
const [state, _setState] = useSafeState(initialState);

return [
state,
Expand All @@ -27,6 +28,7 @@ export function useToggle(

return Boolean(resolveHookState(nextState, prevState));
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []),
];
}

0 comments on commit d181c7f

Please sign in to comment.