惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News - Newest:
Hacker News - Newest: "LLM"
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
H
Heimdal Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
N
News and Events Feed by Topic
H
Hacker News: Front Page
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
SecWiki News
SecWiki News
N
News | PayPal Newsroom
T
Tor Project blog
W
WeLiveSecurity
A
Arctic Wolf
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
月光博客
月光博客
AWS News Blog
AWS News Blog
D
Docker
C
CERT Recently Published Vulnerability Notes
MyScale Blog
MyScale Blog
Google Online Security Blog
Google Online Security Blog
大猫的无限游戏
大猫的无限游戏
T
The Blog of Author Tim Ferriss
I
InfoQ
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
Blog — PlanetScale
Blog — PlanetScale
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
Recorded Future
Recorded Future
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
D
DataBreaches.Net
S
Security Affairs
WordPress大学
WordPress大学
T
Threatpost
Microsoft Security Blog
Microsoft Security Blog
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
B
Blog RSS Feed
Project Zero
Project Zero
P
Proofpoint News Feed

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
Lifecycle methods, hooks, suspense: which's best for fetching in React?
Dmitri Pavlutin · 2019-11-06 · via Dmitri Pavlutin Blog

When performing I/O operations like data fetching, you have to initiate the fetch operation, wait for the response, save the response data to component's state, and finally render.

Async data fetching requires extra-effort to fit into the declarative nature of React. Step by step React improves to minimize this extra-effort.

Lifecycle methods, hooks, and suspense are approaches to fetch data in React. I'll describe them in examples and demos, distill the benefits and drawbacks of each one.

Knowing the ins and outs of each approach makes will make you better at coding async operations.

1. Data fetching using lifecycle methods

The application Employees.org has to do 2 things:

  1. Initially fetch 20 employees of the company.
  2. Filter employees whose name contains a query.

Employees Application

Before implementing these requirements, recall 2 lifecycle methods of a class component:

  1. componentDidMount(): is executed once after mounting
  2. componentDidUpdate(prevProps): is executed when props or state change

<EmployeesPage> implements the fetching logic using these 2 lifecycle methods:


import EmployeesList from "./EmployeesList";

import { fetchEmployees } from "./fake-fetch";

class EmployeesPage extends Component {

constructor(props) {

super(props);

this.state = { employees: [], isFetching: true };

}

componentDidMount() {

this.fetch();

}

componentDidUpdate(prevProps) {

if (prevProps.query !== this.props.query) {

this.fetch();

}

}

async fetch() {

this.setState({ isFetching: true });

const employees = await fetchEmployees(this.props.query);

this.setState({ employees, isFetching: false });

}

render() {

const { isFetching, employees } = this.state;

if (isFetching) {

return <div>Fetching employees....</div>;

}

return <EmployeesList employees={employees} />;

}

}


Open the demo and explore how <EmployeesPage> fetches data.

<EmployeesPage> has an async method fetch() that handles fetching. When fetching request completes, the component state updates with fetched employees.

this.fetch() is executed inside componentDidMount() lifecycle method: this starts fetching the employees when the component is initially rendered.

When the user enters a query into the input field, the query prop is updated. Every time it happens, this.fetch() is executed by componentDidUpdate(): which implements the filtering of employees.

While lifecycle methods are relatively easy to grasp, class-based approach suffers from boilerplate code and reusability difficulties.

Benefits

Intuitive
It's easy to understand: lifecycle method componentDidMount() initiates the fetch on first render and componentDidUpdate() refetches data when props change.

Drawbacks

Boilerplate code
Class-based component requires "ceremony" code: extending the React.Component, calling super(props) inside constructor(), etc.

this
Working with this keyword is burdensome.

Code duplication
The code inside componentDidMount() and componentDidUpdate() is mostly duplicated.

Hard to reuse
Employees fetching logic is complicated to reuse in another component.

2. Data fetching using hooks

Hooks are a better alternative to class-based fetching. Being simple functions, hooks don't have a "ceremony" code and are more reusable.

Let's recall useEffect(callback[, deps]) hook. This hook executes callback after mounting, and after subsequent renderings when deps change.

In the following example <EmployeesPage> uses useEffect() to fetch employees data:


import React, { useState } from 'react';

import EmployeesList from "./EmployeesList";

import { fetchEmployees } from "./fake-fetch";

function EmployeesPage({ query }) {

const [isFetching, setFetching] = useState(false);

const [employees, setEmployees] = useState([]);

useEffect(function fetch() {

(async function() {

setFetching(true);

setEmployees(await fetchEmployees(query));

setFetching(false);

})();

}, [query]);

if (isFetching) {

return <div>Fetching employees....</div>;

}

return <EmployeesList employees={employees} />;

}


Open the demo and look at how the useEffect() fetches data.

You can see <EmployeesPage> using hooks simplified considerable compared to the class version.

Inside <EmployeesPage> functional component useEffect(fetch, [query]) executes fetch callback after the initial render. Also, fetch gets called after later renderings, but only if query prop changes.

But there's still room for improvement. Hooks allow you to extract the employees fetching logic from <EmployeesPage> component. Let's do that:


import React, { useState } from 'react';

import EmployeesList from "./EmployeesList";

import { fetchEmployees } from "./fake-fetch";

function useEmployeesFetch(query) {

const [isFetching, setFetching] = useState(false);

const [employees, setEmployees] = useState([]);

useEffect(function fetch {

(async function() {

setFetching(true);

setEmployees(await fetchEmployees(query));

setFetching(false);

})();

}, [query]);

return [isFetching, employees];

}

function EmployeesPage({ query }) {

const [employees, isFetching] = useEmployeesFetch(query);

if (isFetching) {

return <div>Fetching employees....</div>;

}

return <EmployeesList employees={employees} />;

}


The jungle, bananas and monkeys were extracted to useEmployeesFetch(). The component <EmployeesPage> is not cluttered with fetching logic, but rather does its direct job: render UI elements.

What's better, you can reuse useEmployeesFetch() in any other component that requires fetching employees.

Benefits

Plain and simple
Hooks are free of boilerplate code because they are plain functions.

Reusability
Fetching logic implemented in hooks is easy to reuse.

Drawbacks

Entry barrier
Hooks are slighly counter-intuitive, thus you have to make sense of them before usage. Hooks rely on closures, so be sure to know them well too.

Imperative
With hooks, you still have to use an imperative approach to perform data fetching.

3. Data fetching using suspense

Suspense provides a declarative approach to asynchronously fetch data in React.

Note: Suspense is at an experimental stage, as of November 2019.

<Suspense> wraps a component that performs an async operation:


<Suspense fallback={<span>Fetch in progress...</span>}>

<FetchSomething />

</Suspense>


When fetch is in progress, suspense renders fallback prop content. Later when fetching is completed, suspense renders <FetchSomething /> with fetched data.

Let's see how the employees' application works with suspense:


import React, { Suspense } from "react";

import EmployeesList from "./EmployeesList";

function EmployeesPage({ resource }) {

return (

<Suspense fallback={<h1>Fetching employees....</h1>}>

<EmployeesFetch resource={resource} />

</Suspense>

);

}

function EmployeesFetch({ resource }) {

const employees = resource.employees.read();

return <EmployeesList employees={employees} />;

}


Open the demo and check how suspense works.

<EmployeesPage> uses suspense to handle the fetching inside component <EmployeesFetch>.

resource.employees inside <EmployeesFetch> is a specially wrapped promise that communicates in background with suspense. This way suspense knows how long to "suspend" rendering of <EmployeesFetch>, and when the resource is ready, give it a go.

Here's the big win: Suspense handles async operations in a declarative and synchronous way.

The components are not cluttered with details of how data is fetched. Rather they are declaratively using the resource to render the content. No lifecycles, no hooks, no async/await, no callbacks inside of the components: just rendering a resource.

Benefits

Declarative
Suspense lets you declaratively perform async operations in React.

Simplicity
Declarative code is simple to work with. The components are not cluttered with details of how data is fetched.

Loose coupling with fetching implementation
The components that use suspense don't know how data is fetched: using REST or GraphQL. Suspense sets a boundary that protects fetching details to leak into your components.

No race conditions
If multiple fetching operations were started, suspense uses the latest fetching request.

Drawbacks

Need of Adapters
Suspense requires specialized fetching libraries or adapters that implement the suspense fetching interface.

4. Key takeaways

Lifecycle methods had been for a long time the only solution to fetching. However fetching using them has problems with lots of boilerplate code, duplication, and reusability difficulties.

Fetching using hooks is a better alternative: way less boilerplate code.

Suspense's benefit is declarative fetching. Your components are not cluttered with fetching implementation details. Suspense is closer to the declarative nature of React itself.

Which data fetching approach do you prefer?