0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

よく使いそうなReact Hooksの学習

Posted at

はじめに

Reactでお馴染みのよく使いそうなHooksを簡単にまとめてみました

useState(状態の管理)

■ 主な使い所

  • カウント
  • フォームの値
  • 表示・非表示の切り替え

■使い方

jsx
import { useState } from 'react';

const Counter = () => {
    const [count, setCount] = useState(0);
    return (
        <div>
            <p>カウント: {count}</p>
            <button onClick={() => setCount(count + 1)}>+1</button>
        </div>
    );
};

■ポイント

  • useStateは非同期的に動作する
  • オブジェクトや配列を扱うときはスプレッド演算子を使って更新する

useEffect(副作用処理)

■主な使い所

  • 初回マウント時のAPI呼び出し
  • 値が変化した時に処理を走らせる
  • イベントの登録・解除

■使い方

jsx
import { useEffect, useState } from 'react';

const UserInfo = () => {
    const [user, setUser] = useState(null);

    useEffect(() => {
    fetch('/api/user')
        .then((res) => res.json())
        .then((data) => setUser(data));
    }, []);

    return <div>{user ? user.name : '読み込み中...'}</div>;
};

■ポイント

  • 第2引数の依存配列が重要。空の配列[]なら初回のみ
  • 依存配列の設定ミスで無限ループになることがあるので注意

useContext(グローバルな値)

■主な使い所

  • ログイン中のユーザー情報
  • アプリ全体でのテーマ設定
  • 言語切り替え

■使い方

jsx
// context.js
import { createContext } from 'react';
export const ThemeContext = createContext('light');

// App.js
<ThemeContext.provider value="dark">
    <Child />
</ThemeContext.Provider>

// Child.jsx
import { useContext } from 'react';
import { ThemeContext } from './context';

const Child = () => {
    const theme = useContext(ThemeContext);
    return <div>現在のテーマ: {theme}</div>;
};

■ポイント

  • ネストが深くなる場合はContextの数を絞るか、カスタムHookで抽象化する

useRef(DOMへのアクセス・前回値の保持)

■主な使い所

  • inputへのフォーカス
  • 前回の値を保持したいとき
  • setIntervalのID保持など

■使い方

jsx
import { useRef } from 'react';
const FocusInput = () => {
    const inputRef = useRef(null);

    const handleClick = () => {
    inputRef.current.focus();
    };

    return (
        <>
            <input ref={inputRef} />
            <button onClick={handleClick}>フォーカス</button>
        </>
    );
};

■ポイント

  • useRefの変更は再レンダリングを発生させない

useCallback(関数のメモ化)

■主な使い所

  • 同じ関数インスタンスを保ちたいとき
  • 子コンポーネントの無駄な再レンダリングを防ぐ

■使い方

jsx
import { useCallback, useState } from 'react';

const Parent = () => {
    const [count, setCount] = useState(0);

    const increment = useCallback(() => {
        setCount((p) => p + 1);
    }, []);

    return <Child onClick={increment} />;
};

const Child = React.memo(({ onClick })) => {
    console.log('Child再レンダリング');
    return <button onClick={onClick}>+1</button>;    
});

■ポイント

  • useCallbackとReact.memoはセットで使うと効果的
  • 状態やpropsを依存配列に忘れず指定

終わりに

React Hooksの使い方をマスターすることに「どのHooksを使えば、よりシンプルで保守しやすいコードになるのか?」を考える指針になる
その他にも、色々なHooksや独自のカスタムHooksなどあるので今後はそちらの方も学習していきたい
Hooksを制するものはReactを制する!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?