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