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

echars 3D map solution for custom colors of regions

Table of contents question extend Solving the pro...

How to use module fs file system in Nodejs

Table of contents Overview File Descriptors Synch...

W3C Tutorial (11): W3C DOM Activities

The Document Object Model (DOM) is a platform, a ...

...

Several ways to submit HTML forms_PowerNode Java Academy

Method 1: Submit via the submit button <!DOCTY...

How to use Linux paste command

01. Command Overview The paste command will merge...

Use pure CSS to create a pulsating loader effect source code

Effect Preview Press the "Click to Preview&q...

The implementation process of extracting oracle data to mysql database

In the migration of Oracle database to MySQL data...

Detailed explanation of Linux tee command usage

The tee command is mainly used to output to stand...

Implementation of building custom images with Dockerfile

Table of contents Preface Introduction to Dockerf...

13 JavaScript one-liners that will make you look like an expert

Table of contents 1. Get a random Boolean value (...

Detailed explanation of Truncate usage in MYSQL

This article guide: There are two ways to delete ...

js uses Canvas to merge multiple pictures into one implementation code

Solution function mergeImgs(list) { const imgDom ...