Skip to content

Instantly share code, notes, and snippets.

@lixiaoyan
Last active July 15, 2024 09:13
Show Gist options
  • Save lixiaoyan/804e6710957e447c1c3ad860de55fd83 to your computer and use it in GitHub Desktop.
Save lixiaoyan/804e6710957e447c1c3ad860de55fd83 to your computer and use it in GitHub Desktop.
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