Dashboard sipadu mbip
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

useStableMemo.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { useRef } from 'react';
  2. function isEqual(a, b) {
  3. if (a.length !== b.length) return false;
  4. for (var i = 0; i < a.length; i++) {
  5. if (a[i] !== b[i]) {
  6. return false;
  7. }
  8. }
  9. return true;
  10. }
  11. /**
  12. * Identical to `useMemo` _except_ that it provides a semantic guarantee that
  13. * values will not be invalidated unless the dependencies change. This is unlike
  14. * the built in `useMemo` which may discard memoized values for performance reasons.
  15. *
  16. * @param factory A function that returns a value to be memoized
  17. * @param deps A dependency array
  18. */
  19. export default function useStableMemo(factory, deps) {
  20. var isValid = true;
  21. var valueRef = useRef(); // initial hook call
  22. if (!valueRef.current) {
  23. valueRef.current = {
  24. deps: deps,
  25. result: factory() // subsequent calls
  26. };
  27. } else {
  28. isValid = !!(deps && valueRef.current.deps && isEqual(deps, valueRef.current.deps));
  29. }
  30. var cache = isValid ? valueRef.current : {
  31. deps: deps,
  32. result: factory() // must update immediately so any sync renders here don't cause an infinite loop
  33. };
  34. valueRef.current = cache;
  35. return cache.result;
  36. }