Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

38 строки
1.1 KiB

  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. * useImmediateUpdateEffect(() => {
  14. * setValue(value)
  15. * }, [value])
  16. * ```
  17. *
  18. * @category effects
  19. */
  20. function useImmediateUpdateEffect(effect, deps) {
  21. var firstRef = useRef(true);
  22. var tearDown = useRef();
  23. useWillUnmount(function () {
  24. if (tearDown.current) tearDown.current();
  25. });
  26. useStableMemo(function () {
  27. if (firstRef.current) {
  28. firstRef.current = false;
  29. return;
  30. }
  31. if (tearDown.current) tearDown.current();
  32. tearDown.current = effect();
  33. }, deps);
  34. }
  35. export default useImmediateUpdateEffect;