当前位置:网站首页>useState vs useRef 和 useReducer:相同点、不同点和用例
useState vs useRef 和 useReducer:相同点、不同点和用例
2022-06-23 13:36:00 【码道人】

这篇文章解释了 React Hooks —— useState、useRef 和 useReducer 的相同点和不同点,你将了解到它们的基本用法以及不同的用例。
先看看 Hook 的规则
- Hooks 只能从 React 函数的顶层调用
- 不能从嵌套代码(例如循环、条件)中调用 hook
- 也可以从自定义 Hooks 的顶层中调用 Hooks
通常,应该无条件地调用 hook:)
了解useState钩子
useStateHook 可以为函数式组件开发组件状态。
看看下面的代码。
import { useState } from "react";
function AppDemo1() {
const [darkMode,darkModeUpdater]= useState(true);
return (
<div>
<p>{darkMode ? "dark mode on" : "dark mode off"}</p>
<button onClick={() => darkModeUpdater(!darkMode)}>
toggle dark mode
</button>
</div>
);
}useState Hook 返回一个包含两个项目的数组。在示例中,我们实现了一个布尔组件状态,并使用true进行了初始化,
单个参数useState仅在初始渲染周期期间才会被考虑。使用第二个值更新,useState 可以处理从数字到布尔值到对象的各种数据类型,甚至也可以是一个回调函数,在计算后返回值,如果你想在组件第一次渲染时进行拓展计算,这会很有用。
下面的情况下,我们会更偏向于使用 useState
- 如果我们需要在状态变量更改后重新渲染
- 具有简单更新和用例的简单状态 —— 如果状态变得复杂或者我们有不同的方式来更新状态,我们应该考虑使用 useReducer 挂钩
了解useRef 钩子
useRef hook 和 useState hook 相似,但在下面的情况下不同:
下面的情况下,我们会更偏向于使用 useRef
- 更新值不应该重新渲染 UI,否则我们应该使用 useState /useReducer hook
- 当我们想要直接访问 React 组件或 HTML 元素时
- 我们可以将其用作当前属性中的数据持久存储
注意:在渲染期间改变 ref,即从刚才提到的地方以外的地方,可能会引入错误。这同样适用于useState。
看看下面的代码。
import { useEffect, useState, useRef } from "react";
const AppDemo13 = () => {
const [count, setCount] = useState(0);
// Get the previous value (was passed into hook on last render)
const ref = useRef();
// Store current value in ref
useEffect(() => {
console.log("useEffect");
ref.current = count;
}, [count]); // Only re-run if value changes (kind of Component did update)
return (
<div className="App">
<h1>
Now: {count}, before: {ref.current}
</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};了解useReducer 钩子
当你具有涉及多个子值的复杂状态逻辑或下一个状态取决于前一个状态时,useReducer 通常比 useState 更加好用。
看看下面的代码。
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}如果在单个状态上工作并有各种调度程序来更改状态,这种方法将教会我们理解 redux 逻辑的方式。
结论
- 当要管理的状态足够简单时,考虑使用 useState
- 当我们对各种动作有复杂的逻辑和可靠的状态时,使用 useReducer
- useRef 存储和持久化重新渲染的数据并直接访问 DOM 元素,如果你想提高受控输入元素的性能,我们可以使用 useRef 来减少每次击键时的重新渲染量。
边栏推荐
- Low grain prices hurt farmers, low wages hurt farmers!
- How to correctly calculate the number of rows imported into EXCEL (poi/npoi)
- [digital signal processing] linear time invariant system LTI (judge whether a system is a "non time variant" system | case 2)
- 如何正确计算导入Excel的行数(POI/NPOI)
- High quality coding - air quality map visualization
- How do I turn on / off the timestamp when debugging the chrome console?
- Wechat applet pop up the optional menu from the bottom
- JSP_ SSM Wanfu cinema ticket sales management system, including paper [demonstration video]
- Test article
- NFNet:NF-ResNet的延伸,不用BN的4096超大batch size训练 | 21年论文
猜你喜欢

Intelligent digital signage solution

Penetration test - right raising topic

In this year's English college entrance examination, CMU delivered 134 high scores with reconstruction pre training, significantly surpassing gpt3

The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine

Ks007 realizes personal blog system based on JSP
![[in depth understanding of tcapulusdb technology] tcapulusdb construction data](/img/0c/33d9387cd7733a0c6706a73f9535f7.png)
[in depth understanding of tcapulusdb technology] tcapulusdb construction data

Win the championship for 2 consecutive years! ZABBIX ranked first in a number of monitoring software in 2022

Proofs of Elsevier Elsevier Journal (Neptune Neptune) (problems encountered: latex remove the chapter number)

Detailed explanation of serial port, com, UART, TTL, RS232 (485) differences

Actual combat | how to make a slam track truth acquisition device?
随机推荐
[deeply understand tcapulusdb technology] one click installation of tmonitor background
What is the working status of software testing with a monthly salary of 7500
Detailed explanation of kubernetes log monitoring system architecture
ACM Player Illustration leetcode remove element
leetcode:242. 有效的字母异位词
leetcode:42. Rain water connection
Do you know which position in the IT industry has the most girls?
Acquisition of wechat applet JSON for PHP background database transformation
Thinking and Practice on Quality Standardization (suitable for product, development, testing and management post learning)
IEEE transaction journal revision process record
同花顺是股票用的么?现在网上开户安全么?
Flex attribute of wechat applet
Web technology sharing | [Gaode map] to realize customized track playback
How do I turn on / off the timestamp when debugging the chrome console?
[deeply understand tcapulusdb technology] tcapulusdb import data
大厂架构师:如何画一张大气的业务大图?
【深入理解TcaplusDB技术】Tmonitor系统升级
Former amd chip architect roast said that the cancellation of K12 processor project was because amd counseled!
2022 soft science university professional ranking released! Xi'an electric AI ranked higher than Qingbei, and Nantah ranked first in the country!
Proofs of Elsevier Elsevier Journal (Neptune Neptune) (problems encountered: latex remove the chapter number)