Last active
March 18, 2022 08:30
-
-
Save KacperKozak/1152a6e77d3f5c84571b2423d7b8a4e7 to your computer and use it in GitHub Desktop.
useStateEffect - `useState` with dependency list, similar to `useMemo` but you can change state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DependencyList, Dispatch, SetStateAction, useEffect, useRef, useState } from 'react' | |
/** | |
* `useState` with dependency list, similar to `useMemo` but you can change state | |
* | |
* @example const [error, setError] = useStateEffect(!url, [url]); | |
* @example const [table, setTable] = useStateEffect(() => makeTable(data), [data]); | |
*/ | |
export const useStateEffect = <T>( | |
value: T | (() => T), | |
deps: DependencyList, | |
): [T, Dispatch<SetStateAction<T>>] => { | |
const [state, setState] = useState<T>(value) | |
const isInitialMount = useRef(true) | |
useEffect(() => { | |
if (isInitialMount.current) { | |
isInitialMount.current = false | |
} else { | |
setState(value) | |
} | |
}, deps) | |
return [state, setState] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment