5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React】useStateとuseRefの違い

Last updated at Posted at 2021-10-29

useStateとuseRef

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

useState

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

useRef

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

サンプルコード

下記コード内の

  • カウントアップ(useState) ボタンを押下時、 カウント(useState) の表示が更新される
  • カウントアップ(useRef) ボタンを押下時、 カウント(useRef) の表示は更新されない
.tsx
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?