Skip to content

Instantly share code, notes, and snippets.

@KacperKozak
Last active March 18, 2022 08:30
Show Gist options
  • Save KacperKozak/1152a6e77d3f5c84571b2423d7b8a4e7 to your computer and use it in GitHub Desktop.
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
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