Detailed example of using useState in react

Detailed example of using useState in react

useState

useState adds some internal state to a component by calling it in a function component. React will preserve this state across re-renders. useState
It returns a pair of values: the current state and a function that lets you update it, which you can call from within an event handler or somewhere else. It is similar to the class component
this.setState, but it does not merge the new state with the old state.

Next, let's take a look at an example to see how to use useState.

There is a requirement: you need to load an external web page in an iframe .

In the initial code, we use functional components to achieve this requirement, which only requires a simple rendering of an iframe :

import React, { useState } from 'react';

import styles from './index.less';

function Link(props) {
  const { match: { params: { link = '' } = {} } = {} } = props;
  const enCodeUrl = decodeURIComponent(link);
  const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`;
  return (
    <React.Fragment>
        <iframe
          title={link}
          src={url}
          style={{ width: '100%', height: '100%', verticalAlign: 'top' }}
          frameBorder="0"
        />
    </React.Fragment>
  );
}

export default Link;

A new requirement has come. We need to add a loading effect to the page. The implementation method is very simple. Listen to the load event of the iframe to set the start and end of loading .

To achieve this requirement, we need to store the loading status , but functional components do not have their own status, so we have to transform them into class components:

import React from 'react';
import { Spin } from 'antd';

import styles from './index.less';

export default class Link extends React.Component {
  state = {
    //Store loading status iLoading: true,
  };

  linkLoad() {
    // Update loading
    this.setState({ iLoading: false });
  }

  render() {
    const { match: { params: { link = '' } = {} } = {} } = this.props;
    const { iLoading } = this.state;
    const enCodeUrl = decodeURIComponent(link);
    const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`;
    return (
      <React.Fragment>
        <Spin spinning={iLoading} wrapperClassName={styles['iframe-loading']}>
          <iframe
            onLoad = {this.linkLoad.bind(this)}
            title={link}
            src={url}
            style={{ width: '100%', height: '100%', verticalAlign: 'top' }}
            frameBorder="0"
          />
        </Spin>
      </React.Fragment>
    );
  }
}

In order to realize the loading of a page, we need to use class , and we also need to bind this and other cumbersome behaviors . This is just a simple requirement, but we can solve these problems through hooks , and at the same time solve the problem of state reuse between components. We use useState to achieve it .

Import useState
import React, { useState } from 'react';
Define the state // The parameter of useState is the initial value of the state, and setInitLoading is the method to change the state value const [initLoading, setInitLoading] = useState(true);
Update state onLoad = {() => setInitLoading(false)}
The complete code is as follows:

import React, { useState } from 'react';
import { Spin } from 'hzero-ui';

import styles from './index.less';

function Link(props) {
  const { match: { params: { link = '' } = {} } = {} } = props;
  const [initLoading, setInitLoading] = useState(true);
  const enCodeUrl = decodeURIComponent(link);
  const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`;
  return (
    <React.Fragment>
      <Spin spinning={initLoading} wrapperClassName={styles['iframe-loading']}>
        <iframe
          onLoad = {() => setInitLoading(false)}
          title={link}
          src={url}
          style={{ width: '100%', height: '100%', verticalAlign: 'top' }}
          frameBorder="0"
        />
      </Spin>
    </React.Fragment>
  );
}

export default Link;

Let's take a look at the useState precautions below

useState Parameters

The parameters of useState can be either primitive types or object types. When updating the object type, remember to merge the old state, otherwise the old state will be lost.

const [params, setParams] = useState({
  rotate: 0,
  color: "#000000"
});

const handleInputChange = event => {
  const target = event.target;
  setParams({
    ...params,
    [target.name]: target.value
  });
};

State Dependency

If the current state needs to be calculated based on the value of the last updated state, a function is passed to the function that updates the state. The first parameter of this function is the value of the last update, and the calculated result is returned as the return value.

Summarize

The useState hook allows functional components to have state management features, which is similar to the state management of traditional class components, but more concise and does not require the frequent use of this. In the following articles, we will introduce how to combine other hooks to extract business logic so that component code and hooks code can perform their respective functions.

You may also be interested in:
  • Specific use of useRef in React
  • Introduction to useRef and useState in JavaScript

<<:  Database query optimization: subquery optimization

>>:  Detailed example of SpringBoot+nginx to achieve resource upload function

Recommend

CentOS6.8 uses cmake to install MySQL5.7.18

Referring to the online information, I used cmake...

MySQL query redundant indexes and unused index operations

MySQL 5.7 and above versions provide direct query...

Mysql 5.7.17 winx64 installation tutorial on win7

Software version and platform: MySQL-5.7.17-winx6...

Linux remote control windows system program (three methods)

Sometimes we need to remotely run programs on the...

MySQL 5.6.23 Installation and Configuration Environment Variables Tutorial

This article shares the installation and configur...

How to use provide to implement state management in Vue3

Table of contents Preface How to implement Vuex f...

Implementation code for using CSS text-emphasis to emphasize text

1. Introduction In the past, if you wanted to emp...

Tutorial diagram of installing zabbix2.4 under centos6.5

The fixed IP address of the centos-DVD1 version s...

MySQL 8.0.20 compressed version installation tutorial with pictures and text

1. MySQL download address; http://ftp.ntu.edu.tw/...

View the number of files in each subfolder of a specified folder in Linux

count script #!/bin/sh numOfArgs=$# if [ $numOfAr...

How to install redis in docker and set password and connect

Redis is a distributed cache service. Caching is ...

CSS to achieve the image hovering mouse folding effect

CSS to achieve the image hovering mouse folding e...

How to configure two-way certificate verification on nginx proxy server

Generate a certificate chain Use the script to ge...