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

Solution to Nginx session loss problem

In the path of using nginx as a reverse proxy tom...

JavaScript typing game

This article shares the specific code of JavaScri...

MySQL dual-master (master-master) architecture configuration solution

In enterprises, database high availability has al...

Use Typescript configuration steps in Vue

Table of contents 1. TypeScript is introduced int...

Summary of @ usage in CSS (with examples and explanations)

An at-rule is a declaration that provides instruc...

Implementation of react routing guard (routing interception)

React is different from Vue. It implements route ...

Summary of data interaction between Docker container and host

Preface When using Docker in a production environ...

The difference between animation and transition

The difference between CSS3 animation and JS anim...

React uses routing to redirect to the login interface

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

Detailed explanation of incompatible changes of components in vue3

Table of contents Functional Components How to wr...

MySQL slave library Seconds_Behind_Master delay summary

Table of contents MySQL slave library Seconds_Beh...