iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👻

[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

https://codesandbox.io/s/react-ref-data-cx3dj?file=/src/App.tsx

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.

GitHubで編集を提案

Discussion