React hooks introductory tutorial

React hooks introductory tutorial

State Hooks

Examples:

import { useState } from 'react';

function Example() {
 const [count, setCount] = useState(0);
//count: declared variable; setCount: function to change count value; 0: initial value of count return (
  <div>
   <p>You clicked {count} times</p>
   <button onClick={() => setCount(count + 1)}>
    Click me
   </button>
  </div>
 );
}

useState is a hook function that comes with react, and its function is to declare state variables. The parameter received by the useState function is our initial state. It returns an array. The [0]th item in this array is the current state value, and the [1]th item is the method function that can change the state value.
So what we actually did was聲明了一個狀態變量count,把它的初始值設為0,同時提供了一個可以更改count的函數setCount .

When the user clicks the button, we call the setCount function, which receives the new state value as a parameter. The next thing is to leave it to react, which will re-render our Example component.

What if a component has multiple state values?
First of all, useState是可以多次調用的, so we can write it like this:

function ExampleWithManyStates() {
 const [age, setAge] = useState(42);
 const [fruit, setFruit] = useState('banana');
 const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
}

Secondly, the initial value received by useState is not required to be a simple data type such as string/number/boolean. It can receive objects or arrays as parameters. The only point to note is that our previous this.setState merged the states and returned a new state, while useState是直接替換老狀態后返回新狀態.

On the one hand, hook is used directly in function instead of class; on the other hand, each hook is independent of each other, and different components calling the same hook can ensure the independence of their respective states.

How does react ensure the independence of multiple useStates?

The answer is react是根據useState出現的順序來定的. Let’s take a closer look

//First rendering useState(42); //Initialize age to 42
 useState('banana'); //Initialize fruit to banana
 useState([{ text: 'Learn Hooks' }]); //...

 //Second rendering useState(42); //Read the value of the state variable age (the parameter 42 passed at this time is directly ignored)
 useState('banana'); //Read the value of the state variable fruit (the parameter banana is ignored at this time)
 useState([{ text: 'Learn Hooks' }]); //...

React stipulates that we must write hooks at the outermost layer of the function, and cannot write them in conditional statements such as ifelse, to ensure that the execution order of hooks is consistent.

Effect Hooks

Examples:

import { useState, useEffect } from 'react';

function Example() {
 const [count, setCount] = useState(0);

 // Similar to componentDidMount and componentDidUpdate:
 useEffect(() => {
  // Update the document title document.title = `You clicked ${count} times`;
 });

 return (
  <div>
   <p>You clicked {count} times</p>
   <button onClick={() => setCount(count + 1)}>
    Click me
   </button>
  </div>
 );
}

How would we write it without hooks?

class Example extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
   count: 0
  };
 }

 componentDidMount() {
  document.title = `You clicked ${this.state.count} times`;
 }

 componentDidUpdate() {
  document.title = `You clicked ${this.state.count} times`;
 }

 render() {
  return (
   <div>
    <p>You clicked {this.state.count} times</p>
    <button onClick={() => this.setState({ count: this.state.count + 1 })}>
     Click me
    </button>
   </div>
  );
 }
}

The stateful components we write usually have many side effects, such as initiating Ajax requests to obtain data, adding some listener registration and unregistration, manually modifying the DOM, etc. We have previously written these side effect functions in life cycle function hooks, such as componentDidMount, componentDidUpdate, and componentWillUnmount.現在的useEffect就相當與這些聲明周期函數鉤子的集合體. It's one for three.

How to unbind some side effects of useEffect ?

傳給useEffect的副作用函數返回一個新的函數即可. This new function will be executed after the next re-render of the component.

import { useState, useEffect } from 'react';

function FriendStatus(props) {
 const [isOnline, setIsOnline] = useState(null);

 function handleStatusChange(status) {
  setIsOnline(status.isOnline);
 }

 useEffect(() => {
  ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
  // Be sure to pay attention to this order: tell react to perform cleanup after the next re-rendering of the component and before the next call to ChatAPI.subscribeToFriendStatus
  return function cleanup() {
   ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
  };
 });

 if (isOnline === null) {
  return 'Loading...';
 }
 return isOnline ? 'Online' : 'Offline';
}

How to skip some unnecessary side effects functions?

According to the idea in the previous section, these side-effect functions must be executed every time the rendering is re-rendered, which is obviously not economical. How to skip some unnecessary calculations? We just need to pass the second parameter to useEffect. Use the second parameter to tell React to execute the side effect function we passed (the first parameter) only when the value of this parameter changes.

useEffect(() => {
 document.title = `You clicked ${count} times`;
}, [count]); // Only when the value of count changes will the sentence `document.title` be re-executed

When we pass an empty array [] as the second parameter, it is actually equivalent to executing it only during the first rendering. That is the pattern of componentDidMount plus componentWillUnmount. However, this usage may cause bugs, so use it less often.

What other built-in Effect Hooks are there?

useContext
useReducer
useCallback
useMemo
useRef
useImperativeMethods
useMutationEffect
useLayoutEffect

How to write custom Effect Hooks?

Why should we write an Effect Hooks ourselves? This way we can把可以復用的邏輯抽離出來,變成一個個可以隨意插拔的“插銷” I can plug it into the component I want to use.

For example, we can extract the function of judging whether a friend is online from the FriendStatus component written above, and create a new useFriendStatus hook specifically for judging whether a certain ID is online.

import { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
 const [isOnline, setIsOnline] = useState(null);

 function handleStatusChange(status) {
  setIsOnline(status.isOnline);
 }

 useEffect(() => {
  ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
  return () => {
   ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
  };
 });

 return isOnline;
}

At this time, the FriendStatus component can be shortened to:

function FriendStatus(props) {
 const isOnline = useFriendStatus(props.friend.id);

 if (isOnline === null) {
  return 'Loading...';
 }
 return isOnline ? 'Online' : 'Offline';
}

Suppose we have another friend list that also needs to display online information:

function FriendListItem(props) {
 const isOnline = useFriendStatus(props.friend.id);

 return (
  <li style={{ color: isOnline ? 'green' : 'black' }}>
   {props.friend.name}
  </li>
 );
}

This enables組件復用.

taro hooks

It is very simple to use the Hooks API in Taro. Taro's proprietary Hooks (such as usePageScroll, useReachBottom) are introduced from @tarojs/taro, and the framework's own Hooks (such as useEffect, useState) are introduced from the corresponding framework.

import { usePageScroll, useReachBottom } from '@tarojs/taro' // Taro-specific Hooks
import { useState, useEffect } from 'react' // Framework Hooks (Basic Hooks)

This concludes this article on the detailed tutorial on how to get started with react hooks. For more relevant introductory content on react hooks, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React entry-level detailed notes
  • React Native Basics: Initial Use of Flexbox Layout
  • React Native Basics: A Small Step to Debugging React Native Applications
  • Detailed introduction to react-redux plugin
  • Introduction to React Higher-Order Components
  • Do you know these important knowledge points for getting started with React?

<<:  MySql multi-condition query statement with OR keyword

>>:  In-depth interpretation of /etc/fstab file in Linux system

Recommend

VMware 15.5 version installation Windows_Server_2008_R2 system tutorial diagram

1. Create a new virtual machine from VMware 15.5 ...

Introduction and use of js observer mode

Table of contents I. Definition 2. Usage scenario...

Analysis of common usage examples of MySQL process functions

This article uses examples to illustrate the comm...

Explanation of the configuration and use of MySQL storage engine InnoDB

MyISAM and InnoDB are the most common storage eng...

A practical record of encountering XSS attack in a VUE project

Table of contents Preface Discover the cause Cust...

HTML realizes hotel screening function through form

<!doctype html> <html xmlns="http:/...

Do you know the common MySQL design errors?

Thanks to the development of the Internet, we can...

CSS isolation issue in Blazor

1. Environment VS 2019 16.9.0 Preview 1.0 .NET SD...

Solve the cross-domain problem of Vue+SpringBoot+Shiro

Table of contents 1. Configure Vue front end 1. D...

Hadoop 3.1.1 Fully Distributed Installation Guide under CentOS 6.8 (Recommended)

Foregoing: This document is based on the assumpti...

React uses routing to redirect to the login interface

In the previous article, after configuring the we...