5
1

More than 1 year has passed since last update.

【React】useStateとuseRefの違い

Last updated at Posted at 2021-10-29

useStateとuseRef

  • どちらも値を保持することができる

useState

  • 値を更新すると、コンポーネントの再描写が行われる

useRef

  • 値を更新しても、コンポーネントの再描写は行われない

サンプルコード

下記コード内の

  • カウントアップ(useState) ボタンを押下時、 カウント(useState) の表示が更新される
  • カウントアップ(useRef) ボタンを押下時、 カウント(useRef) の表示は更新されない
import * as React from 'react';

const App: React.FC = () => {
  const [count, setCount] = React.useState(0);
  const countRef = React.useRef(0);

  return (
    <div>
      <div>カウント(useState): {count}</div>
      <button onClick={() => setCount(count + 1)}>カウントアップ(useState)</button>

      <div>カウント(useRef): {countRef.current}</div>
      <button onClick={() => countRef.current++}>カウントアップ(useRef)</button>
    </div>
  );
};

export default App;

ふまえて

useStateuseRef を適切に使い分け、無駄なレンダリングを防ぐことが重要である

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1