how are side effects managed in jotai?

242 views Asked by At

I am relatively new to react state management and I want to try jotai , I have read through the docs but I do not see a way for a middleware use, what is the best practice to perform an async operation before passing the state to the reducer? do I just make the async operation inside the component? like so?

const Home = () => {
const [, setData] = useAtom(DataAtom);

const FetchData = async () => {
  const res = await fetch(URL);
  const resJson = await res.json();
  setData(resJson);
};
useEffect(() => {
  FetchData();
}, []);

return (
  <>
    <h3>Fake Users Ftech Using Jotai</h3>
    <UsersList />
  </>
);

};

1

There are 1 answers

0
David Rearte On
const fetchDataAtom = atom(async () => {
  const response = await fetch(URL);
  const data = await response.json();
  return data;
});

function Home() {
  useAtom(fetchDataAtom);
  
  return (
    <>
      <h3>Fake Users Ftech Using Jotai</h3>
      <UsersList />
    </>
  );
}

You can use that async atom from any component in the react tree and the fetch will be done only once. Thats the advantage of fetching from an atom instead of a regular hook

I recommend you to use a server state manager lib like react-query so you can have your server state separated (react-query) from your local state (jotai), that will boost your performance and will make your project easy to grow.