3
头图

Hello everyone, I'm Casson.

Some students like to request initial data in useEffect , like this:

 useEffect(() => {
  fetch(xxx).then(data => setState(data.json()))
}, [])

But React18 this is not recommended.

What's wrong with writing that? If this is not recommended, what is the recommended way?

Let's take a look at this article Dan on reddit how to answer the above question.

Welcome to join the human high-quality front-end framework group , with flying

this is a common problem

Except React , most of the front-end frameworks organized in the form of components have the following similar API :

  • effect
  • didMount / didUpdate

If there is a need to request data during initialization , such frameworks will choose to perform the requested operation in the above callback function and update the state after the data is returned.

So, this is not unique to React . Instead, he is common.

The reason why it is so prominent in React is because React the official guides developers not to write code in this form ( useEffect in strict mode executes the problem of twice amplification).

And React the reason for doing this is for the performance of the project and UX (User Experience).

Let's talk more about the impact of doing this. Note that these effects also apply to other frameworks.

Why is this not recommended?

Race condition needs to be resolved

The first problem faced by requesting data in useEffect is to solve the race condition.

Suppose you have a component User that receives userID as props and displays user information after requesting data with userID .

Here's how you would write it:

 function User({userID}) {
  const [data, setData] = useState(null);

  useEffect(() => {
    const res = await fetch(`https://xxx/${userID}/`);
    setData(res.json());
  }, [userID]);

  if (data) {
    return <div>{data.name}</div>;
  } 
  return null;
}

Here's a hard-to-reproduce development stage bug if userID changes fast enough, multiple different user requests will be initiated.

And which user's data is finally displayed depends on which request returns first. This is the request race problem .

Re-request data after clicking the back button

If the user jumps to a new page and then returns to the current page through the browser back button, he cannot immediately see the page before the jump.

Instead, you may see a white screen - because you need to re-execute useEffect to get the initial data.

The essential reason for this problem is: there is no cache of the initial data.

White screen time when CSR

CSR (Client-Side Rendering, client-side rendering) when requesting data in useEffect , the page is in a blank state before the data is returned.

waterfall problem

If both parent and child components rely on useEffect to obtain initial data rendering, then the entire rendering process is as follows:

  1. Parent component mount
  2. Parent component useEffect execute, request data
  3. Re-render parent component after data is returned
  4. Subcomponent mount
  5. Subcomponent useEffect execute, request data
  6. Re-render child components after data is returned

It can be seen that when the parent component data request is successful, the child component has not even started to render the first screen.

This is the waterfall problem in rendering - the data flows down like a waterfall, and the components that flow to it start to render, which is very inefficient.

Since writing directly useEffect has so many problems, what is the recommended way?

Recommended way

In the Meta company, based on the Relay driver data (but the request data requires the use of GraphQL ), so this architecture is difficult to popularize in the community.

However, now the community has a mature solution for requesting data .

For SSR , you can use Next.js , Remix to take over the data request.

For CSR , you can use React Query , useSWR to take over the data request.

These mature solutions are dedicated to solving the above-mentioned problems.

If you don't want to use these schemes and want to write your own, you can refer to the following two articles in the new document: React

For students who want to read Chinese, you can read the summary I wrote - React's new documentation: Don't abuse effects

Summarize

In this article, we talked about React18 after that, the method of requesting data that is not recommended and the recommended method of requesting data .

The unrecommended way of requesting data not only exists in React , but many front-end frameworks have such problems.


卡颂
3.1k 声望16.7k 粉丝