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

ElementUI implements cascading selector

This article example shares the specific code of ...

Implementation of services in docker accessing host services

Table of contents 1. Scenario 2. Solution 3. Conc...

HTML+CSS+JS sample code to imitate the brightness adjustment effect of win10

HTML+CSS+JS imitates win10 brightness adjustment ...

Detailed explanation of padding and abbreviations within the CSS box model

As shown above, padding values ​​are composite at...

Vue implements bottom query function

This article example shares the specific code of ...

How to import Chinese data into csv in Navicat for SQLite

This article shares with you the specific method ...

How to use vs2019 for Linux remote development

Usually, there are two options when we develop Li...

Centos7.5 configuration java environment installation tomcat explanation

Tomcat is a web server software based on Java lan...

Introduction to the usage of props in Vue

Preface: In Vue, props can be used to connect ori...

Detailed explanation of cross-usage of Ref in React

Table of contents 1. First, let’s explain what Re...

Some properties in CSS are preceded by "*" or "_".

Some properties in CSS are preceded by "*&qu...

In-depth understanding of JavaScript callback functions

Table of contents Preface Quick Review: JavaScrip...

Summary of Common Mistakes in Web Design

In the process of designing a web page, designers...

Steps to solve the MySQL 8.0 time zone problem

Software Version Windows: Windows 10 MySQL: mysql...