iTranslated by AI
[React] The Fact That useRef is Sufficient for Managing Component Data
The Fact That useRef Is Sufficient for Handling Data Inside Components
Check the Operation Here
Source Code
import { useEffect, useRef, useState } from "react";
const Page = () => {
const [_, dispatch] = useState<{}>();
const that = useRef({ count: 1, text1: "", text2: "" }).current;
useEffect(() => {
const handle = setInterval(() => {
++that.count;
dispatch({});
}, 1000);
return () => clearInterval(handle);
}, []);
return (
<>
<input
value={that.text1}
onChange={(e) => {
that.text1 = e.currentTarget.value;
dispatch({});
}}
/>
<input
value={that.text2}
onChange={(e) => {
that.text2 = e.currentTarget.value;
dispatch({});
}}
/>
<div>count:{that.count}</div>
<div>text1:{that.text1}</div>
<div>text2:{that.text2}</div>
</>
);
};
export default Page;
Mass-Producing useState Was Unnecessary
In this program, the data being handled is stored only in the area created by useRef. useState is used solely to retrieve dispatch to trigger re-renders.
The that created from useRef is equivalent to this in a class component.
Actually, this method can be used in most programs. If you want to re-render after updating a variable, you just need to call dispatch.
Benefits of Storing Data in useRef
There is no need to worry about the timing of state updates in useEffect or useCallback. What you have is real-time data. You don't need to list trigger states in the second argument just for variable updates.
Disadvantages of Storing Data in useRef
If you don't check whether the value to be updated is different from the original variable's value before calling dispatch, a re-render will occur even if the content hasn't changed. The disadvantage is that you need to add a check in such potential places, but it's not a lot of effort.
Summary
Yeah, anything goes.
Discussion