app-jotai.ts 795 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // eslint-disable-next-line no-restricted-imports
  2. import {
  3. atom,
  4. Provider,
  5. useAtom,
  6. useAtomValue,
  7. useSetAtom,
  8. createStore,
  9. type PrimitiveAtom,
  10. } from "jotai";
  11. import { useLayoutEffect } from "react";
  12. export const appJotaiStore = createStore();
  13. export { atom, Provider, useAtom, useAtomValue, useSetAtom };
  14. export const useAtomWithInitialValue = <
  15. T extends unknown,
  16. A extends PrimitiveAtom<T>,
  17. >(
  18. atom: A,
  19. initialValue: T | (() => T),
  20. ) => {
  21. const [value, setValue] = useAtom(atom);
  22. useLayoutEffect(() => {
  23. if (typeof initialValue === "function") {
  24. // @ts-ignore
  25. setValue(initialValue());
  26. } else {
  27. setValue(initialValue);
  28. }
  29. // eslint-disable-next-line react-hooks/exhaustive-deps
  30. }, []);
  31. return [value, setValue] as const;
  32. };