当前位置:网站首页>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 来减少每次击键时的重新渲染量。
边栏推荐
- WPF (c) open source control library: newbeecoder Nbexpander control of UI
- 微信小程序之input前加图标
- [deeply understand tcapulusdb technology] tcapulusdb import data
- [deeply understand tcapulusdb technology] tmonitor background one click installation
- 【二级等保】过二级等保用哪个堡垒机品牌好?
- Monitor the cache update of Eureka client
- 【深入理解TcaplusDB技术】TcaplusDB构造数据
- How to ensure long-term stable operation of EDI system
- 2021-04-15
- Ks008 SSM based press release system
猜你喜欢

【课程预告】基于飞桨和OpenVINO 的AI表计产业解决方案 | 工业读表与字符检测

Assembly language interrupt and external device operation --06

【二级等保】过二级等保用哪个堡垒机品牌好?

Input adjustment of wechat applet
![[digital signal processing] linear time invariant system LTI (judge whether a system is a](/img/98/6819646ea602781101ac9994213129.jpg)
[digital signal processing] linear time invariant system LTI (judge whether a system is a "non time variant" system | case 2)

Use xtradiagram Diagramcontrol for drawing and controlling process graphics

Crmeb second open SMS function tutorial

KS008基于SSM的新闻发布系统

MIT 6.031 reading5: version control learning experience

Ks007 realizes personal blog system based on JSP
随机推荐
Web technology sharing | [Gaode map] to realize customized track playback
AI reference kit
【无标题】
Kali use
WPF (c) open source control library: newbeecoder Nbexpander control of UI
PHP receiving and sending data
等保备案是什么意思?应该去哪里办理备案?
Win10 64位系统如何安装SQL server2008r2的DTS组件?
[deeply understand tcapulusdb technology] tcapulusdb import data
ACM Player Illustration leetcode remove element
Actual combat | how to make a slam track truth acquisition device?
Intelligent digital signage solution
How to install the DTS component of SQL server2008r2 on win10 64 bit systems?
As a software testing practitioner, do you understand your development direction?
When pandas met SQL, a powerful tool library was born
Penetration test - right raising topic
系统设计与分析-技术报告-定时清理验证码的一种解决方案
ICML 2022 𞓜 context integrated transformer based auction design neural network
Crmeb second open SMS function tutorial
Ks003 mall system based on JSP and Servlet