Last active
July 15, 2024 09:13
-
-
Save lixiaoyan/804e6710957e447c1c3ad860de55fd83 to your computer and use it in GitHub Desktop.
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 { useState } from "react"; | |
export const useStateWithDeps = <T>( | |
initialState: T | (() => T), | |
deps: unknown[], | |
) => { | |
const [state, setState] = useState(initialState); | |
const [currentDeps, setCurrentDeps] = useState(deps); | |
if (!shallowEqual(deps, currentDeps)) { | |
const newState = getState(initialState); | |
setState(newState); | |
setCurrentDeps(deps); | |
return [newState, setState] as const; | |
} | |
return [state, setState] as const; | |
}; | |
const getState = <T>(initialState: T | (() => T)) => { | |
return typeof initialState === "function" | |
? (initialState as () => T)() | |
: initialState; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment