Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use State Hook in React Hook

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you the relevant knowledge about how to use State Hook in React Hook. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

The following example is used in the introduction to Hook chapter to introduce Hook:

Import React, {useState, useEffect} from 'react';function Example () {const [count, setCount] = useState (0); / / Similar to componentDidMount and componentDidUpdate: useEffect (() = > {/ / Update the document title using the browser API document.title = `You clicked ${count} times`;}); return (

You clicked {count} times

SetCount (count + 1)} > Click me);}

We will begin to learn about Hook by comparing this code with an equivalent class example.

Equivalent class example

If you have used class in React before, this code should look familiar:

Class Example extends React.Component {constructor (props) {super (props); this.state = {count: 0};} render () {return (

You clicked {this.state.count} times

This.setState ({count: this.state.count + 1}) > Click me);}}

The initial value of state is {count: 0}, and when the user clicks the button, we increase the state.count by calling this.setState (). Code snippets of this class will be used as examples throughout the chapter.

Hook and function components

To review, the functional components of React are as follows:

Const Example = (props) = > {/ / you can use Hook return here;}

Or something like this:

Function Example (props) {/ / you can use Hook return here;}

You might have called them "stateless components" before. But now we have introduced the ability to use React state for them, so we prefer to call it a "functional component".

Hook does not work within class. But you can use them instead of class.

What is Hook?

In the new example, the Hook of useState in React is introduced first

Import React, {useState} from 'react';function Example () {/ /...}

What is Hook? Hook is a special function that allows you to "hook in" React features. For example, useState is a Hook that allows you to add state to the React function component. We will learn about other Hook later.

When will I use Hook? If you are writing a function component and realize that you need to add some state to it, the previous practice is that you have to convert it to class. Now you can use Hook in existing function components.

Declare the State variable

In class, we initialize count state to 0 by setting this.state to {count: 0} in the constructor:

Class Example extends React.Component {constructor (props) {super (props); this.state = {count: 0};}

In the function component, we don't have this, so we can't allocate or read this.state. We call useState Hook directly in the component:

Import React, {useState} from 'react';function Example () {/ / declare a state variable called "count" const [count, setCount] = useState (0)

What do you do when you call the useState method? It defines a "state variable". Our variable is called count, but we can call it anything, such as banana. This is a way to save variables when a function is called-useState is a new method that provides exactly the same functionality as this.state in class. In general, variables "disappear" after the function exits, while variables in state are retained by React.

What parameters are required for useState? The only parameter in the useState () method is the initial state. Unlike class, we can assign it using numbers or strings as needed, not necessarily objects. In the example, we only need to use numbers to record the number of user clicks, so we pass 0 as the initial state of the variable. If we want to store two different variables in state, we only need to call useState () twice. )

What is the return value of the useState method? The return value is the current state and the function that updates the state. That's why we wrote const [count, setCount] = useState (). This is similar to this.state.count and this.setState in class, except that you need to get them in pairs. If you are not familiar with the syntax we use, we will introduce it at the bottom of this chapter.

Now that we know what useState does, our example should be easier to understand:

Import React, {useState} from 'react';function Example () {/ / declare a state variable called "count" const [count, setCount] = useState (0)

We declared a state variable called count and set it to 0. React remembers its current value when rendering repeatedly and provides the latest value to our function. We can update the current count by calling setCount.

Be careful

You may wonder: why is it called useState and not createState?

"Create" may not be very accurate because the state is only created when the component is rendered for the first time. The next time we re-render, useState returns our current state. Otherwise it won't be a state! This is one reason why Hook's name always starts with use. We will find out why in the following Hook rules.

Read State

When we want to display the current count in class, we read this.state.count:

You clicked {this.state.count} times

In the function, we can directly use count:

You clicked {count} times

Update State

In class, we need to call this.setState () to update the count value:

This.setState ({count: this.state.count + 1})} > Click me

In the function, we already have the setCount and count variables, so we don't need this:

Summary of setCount (count + 1)} > Click me

Now let's carefully review what we have learned and see if we really understand it.

Import React, {useState} from 'react';function Example () {const [count, setCount] = useState (0); return

You clicked {count} times

SetCount (count + 1)} > Click me);}

The first line-introduces useState Hook from React. It lets us store the internal state in the function component.

Line 4-inside the Example component, we declare a new state variable by calling useState Hook. It returns a pair of values to the variable we named. We named the variable count because it stores the number of clicks. We initialize it to 0 by passing 0 as the only parameter for useState. The second returned value is itself a function. It allows us to update the value of count, so we call it setCount.

Line 9-when the user clicks the button, we pass a new value to setCount. React re-renders the Example component and passes it the latest count.

Tip: what is the use of square brackets?

You may notice that we define a state variable in square brackets

Const [count, setCount] = useState (0)

The name to the left of the equal sign is not part of React API. You can choose your own name:

Const [fruit, setFruit] = useState ('banana')

This JavaScript syntax is called array deconstruction. It means that we have created both fruit and setFruit. The value of fruit is the first value returned by useState, and setFruit is the second value returned. It is equivalent to the following code:

Var fruitStateVariable = useState ('banana'); / / returns an array of two elements var fruit = fruitStateVariable [0]; / the first value in the array var setFruit = fruitStateVariable [1]; / / the second value in the array

When we use useState to define the state variable, it returns an array of two values. The first value is the current state, and the second value is the function that updates the state. Using [0] and [1] to access is a bit confusing because they have a specific meaning. This is why we use array deconstruction.

Tip: use multiple state variables

It is also convenient to declare state variables as a pair of [something, setSomething], because if we want to use multiple state variables, it allows us to give different names to different state variables:

Function ExampleWithManyStates () {/ / declare multiple state variables const [age, setAge] = useState (42); const [fruit, setFruit] = useState ('banana'); const [todos, setTodos] = useState ([{text:' learning Hook'}])

In the above components, we have the local variables age,fruit and todos, and we can update them separately:

Function handleOrangeClick () {/ / and this.setState ({fruit: 'orange'}) are similar to setFruit (' orange');}

You don't have to use multiple state variables. State variables are good for storing objects and arrays, so you can still group related data into groups. However, unlike this.setState in class, updating the state variable always replaces it rather than merges it.

These are all the contents of the article "how to use State Hook in React Hook". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report