28 lines
671 B
TypeScript
28 lines
671 B
TypeScript
2 years ago
|
import { PrimitiveAtom, unstable_createStore, useAtom } from "jotai";
|
||
3 years ago
|
import { useLayoutEffect } from "react";
|
||
3 years ago
|
|
||
|
export const jotaiScope = Symbol();
|
||
|
export const jotaiStore = unstable_createStore();
|
||
3 years ago
|
|
||
|
export const useAtomWithInitialValue = <
|
||
|
T extends unknown,
|
||
2 years ago
|
A extends PrimitiveAtom<T>,
|
||
3 years ago
|
>(
|
||
|
atom: A,
|
||
|
initialValue: T | (() => T),
|
||
|
) => {
|
||
|
const [value, setValue] = useAtom(atom);
|
||
|
|
||
|
useLayoutEffect(() => {
|
||
|
if (typeof initialValue === "function") {
|
||
|
// @ts-ignore
|
||
|
setValue(initialValue());
|
||
|
} else {
|
||
|
setValue(initialValue);
|
||
|
}
|
||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||
|
}, []);
|
||
|
|
||
|
return [value, setValue] as const;
|
||
|
};
|