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

What is React's Hook?

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces what the Hook of React is, and it has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let's take a look at it.

State Hook

This example is used to display a counter. When you click the button, the value of the counter increases:

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

You clicked {count} times

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

In this case, useState is a Hook (we'll talk about what that means later). Add some internal state to the component by calling it in the function component. React retains this state when it renders repeatedly. UseState returns a pair of values: the current state and a function that allows you to update it, which you can call in the event handler or somewhere else. It is similar to the this.setState of the class component, but it does not merge the new state with the old state. We will show an example of comparing useState and this.state in using State Hook.

The only parameter for useState is the initial state. In the above example, our counter starts from zero, so the initial state is 0. It's worth noting that, unlike this.state, the state here doesn't have to be an object-it can be if you need it. This initial state parameter is used only when rendering for the first time.

Declare multiple state variables

You can use State Hook multiple times in a single component:

Function ExampleWithManyStates () {/ / declares multiple state variables! Const [age, setAge] = useState (42); const [fruit, setFruit] = useState ('banana'); const [todos, setTodos] = useState ([{text:' Learn Hooks'}]); / /.}

The syntax of array deconstruction allows us to give the state variable a different name when calling useState. Of course, these names are not part of useState API. React assumes that when you call useState multiple times, you can guarantee that the order in which they are called remains the same each time you render. We will explain again later how it works and in what scenarios it is used.

So, what is Hook?

Hook are functions that allow you to "hook in" features such as React state and lifecycle in function components. Hook cannot be used in class components-this allows you to use React without using class. We don't recommend rewriting all your existing components, but you can start using Hook in new components. )

React has built-in Hook like useState. You can also create your own Hook to reuse state logic between different components. We will introduce these built-in Hook first.

Effect Hook

You may have previously performed data acquisition, subscription, or manual modification of DOM in the React component. We uniformly refer to these operations as "side effects", or simply "actions".

UseEffect is an Effect Hook that adds the ability to manipulate side effects to function components. It has the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in class components, but is merged into a single API.

For example, the following component sets a page title after React updates DOM:

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

You clicked {count} times

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

When you call useEffect, you are telling React to run your "side effect" function after making changes to DOM. Because the side-effect functions are declared within the component, they can access the props and state of the component. By default, React calls side-effect functions after each rendering-including the first rendering.

The side effect function can also specify how to "clear" the side effect by returning a function. For example, use a side effect function in the following component to subscribe to a friend's online status and clear by unsubscribing:

Import React, {useState, useEffect} from 'react';function FriendStatus (props) {const [isOnline, setIsOnline] = useState (null); function handleStatusChange (status) {setIsOnline (status.isOnline);} useEffect () = > {ChatAPI.subscribeToFriendStatus (props.friend.id, handleStatusChange); return () = > {ChatAPI.unsubscribeFromFriendStatus (props.friend.id, handleStatusChange);}; if (isOnline = = null) {return' Loading...';} return isOnline? 'Online':' Offline';}

In this example, React unsubscribes from ChatAPI when the component is destroyed, and then re-executes the side effect function on subsequent renderings. (if the props.friend.id passed to ChatAPI remains unchanged, you can also tell React to skip re-subscription. )

Like useState, you can use useEffect multiple times in a component:

Function FriendStatusWithCounter (props) {const [count, setCount] = useState (0); useEffect () = > {document.title = `You clicked ${count} times`;}); const [isOnline, setIsOnline] = useState (null); useEffect () = > {ChatAPI.subscribeToFriendStatus (props.friend.id, handleStatusChange); return () = > {ChatAPI.unsubscribeFromFriendStatus (props.friend.id, handleStatusChange);};}); function handleStatusChange (status) {setIsOnline (status.isOnline) } / /...

By using Hook, you can organize related side effects within components (such as creating subscriptions and unsubscriptions) without splitting them into different lifecycle functions.

Hook usage rules

Hook are JavaScript functions, but there are two additional rules for using them:

Hook can only be called on the outermost layer of the function. Do not call in loops, conditional judgments, or subfunctions.

Hook can only be called in functional components of React. Do not call in other JavaScript functions. (there is another place to call Hook-- in the custom Hook, which we will learn later. )

Custom Hook

Sometimes we want to reuse some state logic between components. So far, there are two mainstream solutions to this problem: high-level components and render props. Custom Hook allows you to achieve the same goal without adding components.

Earlier, we introduced a component called FriendStatus, which subscribes to a friend's online status by calling the Hook of useState and useEffect. Suppose we want to reuse this subscription logic in another component.

First, we extract this logic into a custom Hook called useFriendStatus:

Import React, {useState, useEffect} from 'react';function useFriendStatus (friendID) {const [isOnline, setIsOnline] = useState (null); function handleStatusChange (status) {setIsOnline (status.isOnline);} useEffect () = > {ChatAPI.subscribeToFriendStatus (friendID, handleStatusChange); return () = > {ChatAPI.unsubscribeFromFriendStatus (friendID, handleStatusChange);};}); return isOnline;}

It takes friendID as a parameter and returns whether the friend is online:

Now we can use it in two components:

Function FriendStatus (props) {const isOnline = useFriendStatus (props.friend.id); if (isOnline = null) {return 'Loading...';} return isOnline? 'Online':' Offline';} function FriendListItem (props) {const isOnline = useFriendStatus (props.friend.id); return ({props.friend.name});}

The state between each component is completely independent. Hook is a way to reuse state logic, it does not reuse state itself. In fact, each call to Hook has a completely separate state-so you can call the same custom Hook multiple times in a single component.

Customizing Hook is more like a convention than a function. If the name of the function starts with use and calls other Hook, we say this is a custom Hook. UseSomething's naming convention allows our linter plug-in to find bug in code that uses Hook.

You can create a custom Hook that covers a variety of scenarios, such as form processing, animation, subscription announcements, timers, and maybe even more. We are looking forward to seeing what kind of custom Hook will appear in the React community.

Other Hook

In addition, there are some less frequently used but useful Hook. For example, useContext allows you to subscribe to React's Context without using component nesting.

Function Example () {const locale = useContext (LocaleContext); const theme = useContext (ThemeContext); / /...}

In addition, useReducer allows you to manage complex state locally in components through reducer.

Function Todos () {const [todos, dispatch] = useReducer (todosReducer); / /. Thank you for reading this article carefully. I hope the article "what is the Hook of React" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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