Come and join us!

“The Newbies of Little and Hill” provides technical information and a series of basic articles for front-end developers. For a better user experience, please move to our official website of Xiaoheshan beginners (https://xhs-rookies.com/) to learn, timely access to the latest articles.

“Code tailor”, if you are interested in our articles or would like to make some suggestions, please follow our official account “newbies of Xiaoheshan” at WeChat, and contact us. You can also view our articles on WeChat. Every suggestion or agreement is a great encouragement to us!

Why do we learn hooks

preface

The main purpose of this article is to look at the use of state hooks (UseState).

useState

define

UseState () is used to introduce state to a function component. Pure functions cannot have state, so hooks are used to introduce state.

How to use

UseState uses the following statements.

Const [Count, setCount] = UseState (DefaultValue) // DefaultValue = 0
let countVariable = useState(0)
let count = countVariable[0]
let setCount = countVariable[1]
setCount(count + 1) // count 1
setCount(10) // count 10
const [name, setName] = useState('xhs')
const [age, setAge] = useState(18)
const [dowhat, setDowhat] = useState({ thing: 'Learn Hooks' })
setName('xxxxxxxhs')
setAge(20)
setDowhat({ thing: 'Learn Nothing' })
import React, { Component } from 'react' import './App.css' export class App extends Component { constructor(props) { super(props) this.state = { count: 0, } } handleWithAddOne() { this.setState({ count: this.state.count + 1 }) } handleWithAddTwo() { this.setState({ count: this.state.count + 2 }) } handleWithDecreaseOne() { this.setState({ count: this.state.count - 1 }) } render() { const { count } = this.state return ( <div className="app"> <p>Now,the number is </p> < p className="button add" onClick={() =>.</p> < p className="button add" onClick={() => this.handleWithAddOne()}> Click it, The number will add 1 </ Button > {/* Count + 2 */} < Button className=" Button add" onClick={() => this.handleWithAddTwo()}> Click it, The number will add 2 < / button > {/ * click * / count - 1} < button className = "button decrease" onClick = {() = > this.handleWithDecreaseOne()}> CLick it, the num will decrease 1 </button> </div> </div> ) } }
.app {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.three-btn {
  display: flex;
  flex-direction: column;
}
​
.button {
  height: 40px;
  margin: 12px 0px;
  color: white;
  border: none;
  border-radius: 10px;
}
.add {
  background-color: #1890ff;
}
​
.decrease {
  background-color: red;
}

Multiple State variables can be defined using multiple UseState.

UseState returns an array, typically using a deconstructive assignment to retrieve the two values, state, and a function that modifies the state. These two values need to be obtained in pairs.

The useState function initializes state by passing in a unique parameter as the default value.

Now, let’s summarize UseState.

summary

In short, UseState provides function components with React State, which can now be called function components. Previously, it was called stateless components.

In this way, we have successfully used UseState, and the result is the same as that of the class component above. The complexity of the code has been greatly reduced, which is probably more acceptable than the class component.

Import './ app.css '// Import the CSS style, Import {useState} from 'react' function App() {const [count, setCount] = useState(0) return ( <div className="app"> <p>Now,the number is {count}.</p> <div className="three-btn"> <button className="button add" onClick={() => setCount(count + 1)}> Click it, the number will add 1 </button> <button className="button add" onClick={() => setCount(count + 2)}> Click it, the number will add 2 </button> <button className="button decrease" onClick={() => setCount(count - 1)}> CLick it, the num will decrease 1 </button> </div> </div> ) }

Let’s complete the requirements:

We’ll create the value of state using UseState, and we’ll change the value of count using setCount.

Rewrite the case using UseState

Let’s take a look at how UseState works.

As we can see from the above, although the effect has been achieved as we expected, it is obvious that the React App is very heavy. In our real project development, the React App is composed of multiple classes, one layer at a time, and the complexity can be imagined. At this point, if we were to add Redux, it would be much more complicated.

This is what it looks like after it was run

The CSS styles

First, let’s look at the case where we use state in a class component. We need to declare count in state and give it a default value of 0. The only way we can change count is through this.setState().

Class components are implemented using this.state

I want to have a simple counter with +1, +2, and -1 operations that refresh the current numer value on the page.

Now that you have a good understanding of UseState, let’s complete a requirement:

Contrast Class Components

How do you modify these variables? As above, you can simply call the respective set methods.

The statement above can only declare one state variable. If you want to declare more than one state variable, you only need to use multiple useState variables.

Multiple state variables are used

So the first time we do setCount, it goes from 0 to > 1, and the second time we do it, we pass in a 10, and it goes from 1 to > 10 so count is updated to 10.

To change the value of state, just use the setCount method directly to make the change. The value passed in is returned directly to the count value and updated. Like the following two.

Change the state

That is, using UseState to return an array, which is equivalent to the following code:

Returns an array, but is composed of two values, the current state and the function that modifies the state, using the JavaScript syntax of the array solution. This is similar to class this.state.count and this.setState, except that you need to get them in pairs.

UseState return value

It defines a state variable named count, which provides exactly the same functionality as this.state in the class. In general, variables “disappear” after the function exits, while variables in the state are retained by React.

What does UstateState do

The only parameter that UseState needs to pass in is the initialization state. We can pass various types of values, such as numbers, characters, arrays, objects, etc.

UseState required parameters

Next day forecast

In the next section, we’ll introduce you to useEffect. Stay tuned!