UNPKG

1.08 kBJavaScriptView Raw
1import { useRef } from 'react';
2import useStableMemo from './useStableMemo';
3import useWillUnmount from './useWillUnmount';
4
5/**
6 * An _immediate_ effect that runs an effect callback when its dependency array
7 * changes. This is helpful for updates should must run during render, most
8 * commonly state derived from props; a more ergonomic version of https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
9 *
10 * ```ts
11 * function Example({ value }) {
12 * const [intermediaryValue, setValue] = useState(value);
13 *
14 * useUpdateImmediateEffect(() => {
15 * setValue(value)
16 * }, [value])
17 * ```
18 *
19 * @category effects
20 */
21function useUpdateImmediateEffect(effect, deps) {
22 const firstRef = useRef(true);
23 const tearDown = useRef();
24 useWillUnmount(() => {
25 if (tearDown.current) tearDown.current();
26 });
27 useStableMemo(() => {
28 if (firstRef.current) {
29 firstRef.current = false;
30 return;
31 }
32 if (tearDown.current) tearDown.current();
33 tearDown.current = effect();
34 }, deps);
35}
36export default useUpdateImmediateEffect;
\No newline at end of file