-
Once the experimental If the React team add the ability to call Note: I can see there is other usage of hook APIs in this function currently so I know it can't happen as simply as I suggest, but I still think it'd be an interesting step forwards to be able to |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 8 replies
-
Yes, I can consider about skipping internal Meanwhile, please use const useAtomValueWithoutUse = (atom) => {
const store = useStore();
const [value, setValue] = useState(() => store.get(atom));
useEffect(() => store.sub(atom, setValue), [store, atom]);
return value;
}; |
Beta Was this translation helpful? Give feedback.
-
Alternatively, you could use import { atom, useAtom } from 'jotai';
import { atomEffect } from 'jotai-effect';
const userDataAtom = atom(null);
const fetchDataEffect = atomEffect((get, set) => {
const abortController = new AbortController();
const { signal } = abortController;
const url = 'https://api.example.com/userdata';
fetch(url, { signal })
.then(response => response.json())
.then(userData => {
set(userDataAtom, userData);
})
.catch(error => {
if (error.name !== 'AbortError') {
console.error('Failed to fetch user data:', error);
}
});
// Cleanup function to abort the fetch
return () => abortController.abort();
});
const userAtom = atom((get) => {
get(fetchDataEffect); // registers fetchDataEffect
return get(userDataAtom);
});
export function UserProfile() {
const [userData] = useAtom(userAtom);
if (!userData) {
return <div>Loading...</div>;
}
return (
<div>
<h1>User Profile</h1>
<p>Name: {userData.name}</p>
<p>Email: {userData.email}</p>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
-
To subscribe to atoms conditionally, I usually do something like this currently. export const voidAtom = atom(() => undefined, () => {
// noop
});
// an atom that could potentially cause a lot of rerendering if used unnecessarily.
const screenHeightAtom: Atom<number> = ...;
// later in the components
function SomeComponent({ responsiveToHeight }: Props) {
// now the components only rerenders once it actually needs to be responsive to the screen's height
const screenHeight = useAtomValue(responsiveToHeight ? screenHeightAtom : voidAtom);
// do the rendering...
} |
Beta Was this translation helpful? Give feedback.
-
jotaijs/jotai-suspense#7 adds |
Beta Was this translation helpful? Give feedback.
Oh, were you talking about it?
Of course, I've thought about it, quite a lot.
There are two hurdles:
use(Observable)
or something alike.use()
calls in a non-hook function.It's very unlikely that both are solved at any time soon. So, consider that we don't have a hope.