生命周期
React 16 Lifecycle Methods: How and When to Use Them
constructor
The first thing that gets called is your component constructor.
Most Common Use Case For Constructor: Setting up state, creating refs and method binding.
getDerivedStateFromProps
When mounting, getDerivedStateFromProps
is the last method called before rendering. You can use it to set state according to the initial props.
Most Common Use Case For getDerivedStateFromProps (during mount): Updating state based on props, when the props themselves aren’t enough.
render
Most Common Use Case For Render: Returning component JSX.
componentDidMount
After we’ve rendered our component for the first time, this method is called.
Most Common Use Case for componentDidMount
: Starting AJAX calls to load in data for your component.
shouldComponentUpdate
shouldComponentUpdate
allows us to say: only update if the props you care about change.
Most Common Use Case: Controlling exactly when your component will re-render.
getSnapshotBeforeUpdate
It’s called between render
and the updated component actually being propagated to the DOM.
Most Common Use Case: Taking a look at some attribute of the current DOM, and passing that value on to componentDidUpdate
.
componentDidUpdate
Most Common Use Case for componentDidUpdate: Reacting to committed changes to the DOM.
componentWillUnmount
Most Common Use Case for componentWillUnmount: Cleaning up any leftover debris from your component.
HOC
Render Props
The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.
Immutable
Immutability in React and Redux: The Complete Guide
Hooks
Hooks 的作用:
Hooks allow you to reuse stateful logic without changing your component hierarchy.
Hooks are a way to reuse stateful logic, not state itself.
Hooks let you use more of React’s features without classes.
Hooks let us split the code based on what it is doing rather than a lifecycle method name.
背景
React doesn’t offer a way to “attach” reusable behavior to a component.
Introducing Hooks – React
什么时候使用 Hook ?
If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component.
类似方案
Render Props – React
Higher-Order Components – React
useState
vs this.state
useEffect
vs lifecycles
Rules of Hooks
- Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
- Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks — your own custom Hooks.)
State Hook
用法
Declaring a State Variable
1 | import React, { useState } from 'react'; |
The only argument to the useState()
Hook is the initial state.
It returns a pair of values: the current state and a function that updates it.
Reading State
class:
1 | <p>You clicked {this.state.count} times</p> |
function:
1 | <p>You clicked {count} times</p> |
Updating State
class:
1 | <button onClick={() => this.setState({ count: this.state.count + 1 })}> |
function:
1 | <button onClick={() => setCount(count + 1)}> |
Effect Hook
useEffect
, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount
, componentDidUpdate
, and componentWillUnmount
in React classes, but unified into a single API.
Tips
You can think of useEffect
Hook as componentDidMount
, componentDidUpdate
, and componentWillUnmount
combined.
Side Effect
Data fetching, subscriptions, or manually changing the DOM from React components. We call these operations “side effects”. because they can affect other components and can’t be done during rendering.
There are two common kinds of side effects in React components: those that don’t require cleanup, and those that do.
Compare Classes
In React class components, the render
method itself shouldn’t cause side effects. It would be too early — we typically want to perform our effects after React has updated the DOM.
We put side effects into componentDidMount
and componentDidUpdate
.
Example Using Hooks
1 | import React, { useState, useEffect } from 'react'; |
What does useEffect do?
Tell React that your component needs to do something after render.
Why is useEffect called inside a component?
Placing useEffect
inside the component lets us access the count state variable (or any props) right from the effect.
Does useEffect run after every render?
Yes! By default. But you can customize this.
Effects with Cleanup
有些情况下我们需要清除 sideEffect。在 Classes 的写法中,我们在 componentWillUnmount
中处理该逻辑。
Hook 的写法:
If your effect returns a function, React will run it when it is time to clean up:
1 | import React, { useState, useEffect } from 'react'; |
Why did we return a function from our effect?
This is the optional cleanup mechanism for effects.
When exactly does React clean up an effect?
React performs the cleanup when the component unmounts.
However, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.
Tips
使用多个 useEffect
可以将不同的逻辑分别在不同的 useEffect
中处理,而不必像生命周期的写法将它们揉在一起。
Why Effects Run on Each Update
You might be wondering why the effect cleanup phase happens after every re-render.
Explanation: Why Effects Run on Each Update
Optimizing Performance by Skipping Effects
Optimizing Performance by Skipping Effects
Building Your Own Hooks
Middleware
Redux
redux-thunk
redux-saga
Fiber
CSS in React
Modular CSS with React - Philippe Masset - Medium
4. Four ways to style react components - codeburst
5 Ways to Style React Components in 2019 - Bits and Pieces
相关链接
Presentational and Container Components
Container Components
RFC: React Hooks by sebmarkbage · Pull Request #68 · reactjs/rfcs
Hooks FAQ – React
Lazy loading (and preloading) components in React 16.6
React v16.2.0: Improved Support for Fragments
React Interview Questions
Everything You Should Know About React: The Basics You Need to Start Building
关于React v16.3 新生命周期 - 掘金
How to Benchmark React Components: The Quick and Dirty Guide
what-is-the-purpose-of-callback-function-as-an-argument-of-setstate
what-is-the-difference-between-html-and-react-event-handling
what-is-the-use-of-refs
What are forward refs?
What are the different phases of component lifecycle?
How to create props proxy for HOC component?
What is children prop?
What is the purpose of using super constructor with props argument?
What are fragments?
Why fragments are better than container divs?
What are error boundaries in React v16?
How to use innerHTML in React?
What will happen if you use props in initial state?
How you use decorators in React?
What are the lifecycle methods going to be deprecated in React v16?
Why we need to pass a function to setState()?
Can you force a component to re-render without calling setState?
What is the difference between super() and super(props) in React using ES6 classes?
What is the difference between setState() and replaceState() methods?
What is the recommended approach of removing an array element in React state?
How to focus an input element on page load?
What are the possible ways of updating objects in state?
How to programmatically trigger click event in React?
How to make AJAX call and in which component lifecycle methods should I make an AJAX call?
How to perform automatic redirect after login?