Hacker News new | past | comments | ask | show | jobs | submit login

As a misuser on hobby projects, what is the best way to do an initial API call once the main component has mounted?

I was using useEffect, with the deps being the things sent to the query.




It seems mostly expected to have a framework or library in place that takes care of data fetching for the root component.

The new docs emphasize this, I guess mostly to make users think twice about building their own hook and to make it easy to move initial data fetching to the server.

Frameworks include next.js, remix or vite-plugin-ssr (the last one is maybe an outlier, as it deems itself a library).

Often fetching is tied to routing, which makes sense.

If routing is not needed, AFAIK the go-to solutions right now are react-query or SWR.

https://swr.vercel.app/

react-query has a nice comparison table for data fetching libraries:

https://tanstack.com/query/v4/docs/react/comparison

If routing only takes place on the client, react-router also includes data fetching features:

https://reactrouter.com/en/main/guides/data-libs

I don't know how well react-router fits with SSR.

If none of that fits and the requirements are either very simple or very custom, it should still be possible to manually pass props to the root component.

Looking this up in the docs, the big caveat of this unconventional approach is that props would not be reactive, the root component would have to be manually re-rendered:

https://react.dev/reference/react-dom/client/createRoot#upda...


For what it's worth, "the deps being the things sent to the query" is fundamentally correct. What were you doing wrong before and what are you doing now? There are alternatives to making queries with useEffect which can result in a better user experience. Were you alluding to those?

One of the sources of confusion I see the most around effects is that people still think of them in terms of components mounting and unmounting. However, effects only care about running, cleaning up, and maybe needing to run again. I can't think of a case when they'd need to know about the component's mount/unmount behavior.

For effects, the main things to consider are:

• Can this effect be fired unconditionally, and if not, what could change in the system to make its result inconsistent/outdated with the new state of the system?

• What cleanup does this effect need?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: