Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a server side data fetching with React Hooks

We just start moving into React Hooks from the React life-cycle and one of the things that we noticed, is that there's no straightforward way to run something similar to ComponentWillMount for loading data before sending the rendered page to the user (since useEffect is not running on SSR).

Is there any easy way supported by React to do so?

like image 763
Idan Gozlan Avatar asked Dec 05 '19 01:12

Idan Gozlan


1 Answers

I had the same problem. I've managed to solve it with a custom hook and by rendering application twice on the server-side. The whole process looks like this:

  • during the first render, collect all effects to the global context,
  • after first render wait for all effects to resolve,
  • render the application for the second time with all data.

I wrote an article with examples describing this approach. This is a direct link to the example form article on CodeSandbox.

Also, I have published an NPM package that simplifies this process - useSSE on GitHub.

like image 177
cosma Avatar answered Sep 23 '22 11:09

cosma