5

With React 18 Strict mode, useEffect runs twice, so data fetching in useEffect without workarounds is not good. I watched some videos, read some articles saying that we shouldn't fetch data in this hook, however I have not seen practical examples about how to correctly do it. This is how I do on react 17:

  • I have a Zustand store, and it contains the action that will fetch data and populate my state in the store
{
  itens: [],
  loading: false,
  error: null,
  async fetchItens(page: number) {
    try {
      set({
        loading: true,
        error: null
      });

      const { data } = await axios.get(`my-url`);
      set({
       loading: false,
       itens: data,
      })
    } catch(err) {
      set({
        error: "There was an error.",
        loading: false,
      })
    } 
  }
}

And in my component I call it like this:

function MyComponent() {
  const itens = useStore(state => state.itens);
  const loading = useStore(state => state.loading);
  const error = useStore(state => state.error);
  const fetchItens = useStore(state => state.fetchItens);

  useEffect(() => {
     fetchItens();
  }, []);

  if(loading) {
    return <div>Loading...</div>;
  }

  if(error) {
    return <div>{error}</div>
  }

  return (
    <div>
      {itens.map(item => <span>{item}</span>)}
    </div>
  );
}

How would I do something like this in React 18?

otavio1992
  • 712
  • 2
  • 6
  • 18
  • Fetching data should be idempotent, and the double runs only happen in dev mode (to catch errors early), so this really is a non-issue if you ask me. – AKX Jun 16 '22 at 12:42
  • 1
    I would recommend to check redux-toolkit query, that library simplify and speed a lot your development and also it's relatively easy to learn – Osmanys Fuentes-Lombá Jun 16 '22 at 13:16
  • The thing is sometimes I don't want to cache the data. For example, right now I'm working on a react native app that makes sales. I have a shopping cart that is in my Zustand store, and this cart references data that is fetched from the api. So for me it makes sense that both stays inside Zustand, so I can access them easily. Also since I work with sales of seats for events, I can't cache that data, it should always be fresh so that no unavailable seats are shown (even for a second while the fetch library revalidates the data). – otavio1992 Jun 16 '22 at 16:21
  • Does it solve your issue? https://beta.reactjs.org/learn/you-might-not-need-an-effect#fetching-data – NineCattoRules Jan 22 '23 at 13:41

0 Answers0