当前位置:网站首页>Usestate vs useref and usereducer: similarities, differences and use cases
Usestate vs useref and usereducer: similarities, differences and use cases
2022-06-23 15:27:00 【Code Taoist】

This article explains React Hooks —— useState、useRef and useReducer The similarities and differences of , You will learn about their basic usage and different use cases .
Have a look first Hook The rules of
- Hooks Only from React Top level calls to functions
- You cannot start from nested code ( For example, circulation 、 Conditions ) Call in hook
- You can also customize Hooks Called from the top level of Hooks
Usually , Should call unconditionally hook:)
understand useState hook
useStateHook You can develop component states for functional components .
Take a look at the code below .
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 Returns an array containing two items . In the example , We implemented a Boolean component state , And use true It's initialized ,
Single parameter useState Only considered during the initial render cycle . Update... With the second value ,useState You can handle data types from numbers to Booleans to objects , It can even be a callback function , Return value after calculation , If you want to expand the calculation when the component is rendered for the first time , It would be useful .
In the following cases , We would prefer to use useState
- If we need to re render after the state variable changes
- Simple state with simple updates and use cases —— If the state becomes complex or we have different ways to update the State , We should consider using useReducer hook
understand useRef hook
useRef hook and useState hook be similar , But it is different in the following cases :
In the following cases , We would prefer to use useRef
- Updated values should not be re rendered UI, Otherwise we should use useState /useReducer hook
- When we want direct access to React Component or HTML Element time
- We can use it as a persistent store of data in the current attribute
Be careful : Change during rendering ref, That is, from places other than those just mentioned , Errors may be introduced . This also applies to useState.
Take a look at the code below .
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>
);
}; understand useReducer hook
When you have complex state logic involving multiple sub values or the next state depends on the previous state ,useReducer Often than useState A more useful .
Take a look at the code below .
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>
</>
);
}If you work on a single state and have various schedulers to change the State , This method will teach us to understand redux In a logical way .
Conclusion
- When the state to be managed is simple enough , Consider using useState
- When we have complex logic and reliable states for various actions , Use useReducer
- useRef Store and persist the re rendered data and access it directly DOM Elements , If you want to improve the performance of controlled input elements , We can use useRef To reduce the amount of re rendering per keystroke .
边栏推荐
- JS里的数组
- JS垃圾回收
- Summary of operating system underlying knowledge (interview)
- Mysql数据库---日志管理、备份与恢复
- Mysql database - log management, backup and recovery
- Ie mode of selenium edge
- 腾讯云服务器发送邮件失败
- 列表查询排序参数处理
- The team of China University of Mines developed an integrated multi-scale deep learning model for RNA methylation site prediction
- golang 重要知识:atomic 原子操作
猜你喜欢

Moher College - manual SQL injection vulnerability test (MySQL database)

Important knowledge of golang: mutex

After nine years at the helm, the founding CEO of Allen Institute retired with honor! He predicted that Chinese AI would lead the world

golang 重要知识:sync.Once 讲解

JS里的数组

Arrays in JS
Sorting out and summarizing the handling schemes for the three major exceptions of redis cache

重卡界销售和服务的“扛把子”,临沂广顺深耕产品全生命周期服务

Important knowledge of golang: sync Once explanation
![[datahub] LinkedIn datahub learning notes](/img/ca/9c4a87d38155edd093cbb81d81ee81.png)
[datahub] LinkedIn datahub learning notes
随机推荐
php 二维数组插入
[datahub] LinkedIn datahub learning notes
Detailed steps for MySQL dual master configuration
Summary of operating system underlying knowledge (interview)
MySQL高级语句二
After nine years at the helm, the founding CEO of Allen Institute retired with honor! He predicted that Chinese AI would lead the world
[普通物理] 半波损失 等厚与等倾干涉
Arrays in JS
2021-05-22
The largest IPO of Hong Kong stocks this year, with a net worth of 66billion, is the "King" sitting on the mine
2021-06-07
golang 重要知识:atomic 原子操作
直播间源码在开发前期必须做的工作及开发步骤
Moher College - manual SQL injection vulnerability test (MySQL database)
Error creating bean with name xxx Factory method ‘sqlSessionFactory‘ threw exception; nested excepti
How can genetic testing help patients fight disease?
Starting from 3, add paging function in the business system
聚合生态,使能安全运营,华为云安全云脑智护业务安全
How is it safe to open an account for futures? Which futures company has a relatively low handling fee for futures and is suitable for retail investors to open an account?
Tencent ECS failed to send email