Skip to content

Commit

Permalink
fix(useSetState): memoize setState callback
Browse files Browse the repository at this point in the history
  • Loading branch information
TylerR909 committed Aug 23, 2019
1 parent c73e92f commit 16f023f
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/useSetState.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { useState } from 'react';
import { useState, useCallback } from 'react';

const useSetState = <T extends object>(
initialState: T = {} as T
): [T, (patch: Partial<T> | ((prevState: T) => Partial<T>)) => void] => {
const [state, set] = useState<T>(initialState);
const setState = patch => {
set(prevState => Object.assign({}, prevState, patch instanceof Function ? patch(prevState) : patch));
};
const setState = useCallback(
patch => {
set(prevState => Object.assign({}, prevState, patch instanceof Function ? patch(prevState) : patch));
},
[set]
);

return [state, setState];
};
Expand Down

0 comments on commit 16f023f

Please sign in to comment.