React Hooksの基本をわかりやすくまとめてみた

React

やりたいこと

Reactを学習中に、Hooksの使い方がわからなくなったので、基本的なHooksをまとめて整理します。

useState

概要

関数コンポーネントで状態(state)を管理するためのHookです。

構文

  • state: 現在の状態を保持する変数
  • setState: 状態を更新するための関数
  • initialState: 状態の初期値
JSX
const [state, setState] = useState(initialState);

使用例

JSX
import React, { useState } from 'react';

function ExampleComponent() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment Count
      </button>
    </div>
  );
}

export default ExampleComponent;

useEffect

概要

コンポーネントの表示や更新時に特定の処理を実行したいときに使います。

構文

  • 第1引数:実行したい処理
  • 第2引数:依存関係の配列。ここで指定した変数が変わったときだけ関数が実行されます。
JSX
useEffect(() => {
  実行したい処理(第1引数)
}, [依存する変数の配列(第2引数)]);

使用例

JSX
import React, { useState, useEffect } from 'react';

function ExampleComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log(`Count changed: ${count}`);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment Count
      </button>
    </div>
  );
}

export default ExampleComponent;

useContext

概要

コンポーネント間でデータを共有するために使うHookです。これを使うと、深いコンポーネント階層でも直接データを渡せます。

構文

  • context: 作成したコンテキストオブジェクト
JSX
const value = useContext(context);

使用例

JSX
import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext();

const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

const ThemeButton = () => {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <button onClick={toggleTheme} style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
      Toggle Theme
    </button>
  );
};

const App = () => {
  return (
    <ThemeProvider>
      <div>
        <h1>Hello, useContext!</h1>
        <ThemeButton />
      </div>
    </ThemeProvider>
  );
};

export default App;

useReducer

概要

複雑な状態管理を行うときに使うHookです。useStateよりも細かい制御ができます。

構文

  • reducer: 状態を更新するための関数
  • state: 現在の状態
  • dispatch: 状態を更新する関数
JSX
const [state, dispatch] = useReducer(reducer, initialState);

使用例

JSX
import React, { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function ExampleComponent() {
  const initialState = { count: 0 };
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>
        Increment Count
      </button>
      <button onClick={() => dispatch({ type: 'decrement' })}>
        Decrement Count
      </button>
    </div>
  );
}

export default ExampleComponent;

useRef

概要

再レンダリング間で値を保持したり、DOM要素に直接アクセスしたいときに使います。

構文

JSX
const refContainer = useRef(initialValue);

使用例

JSX
import React, { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef(null);

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

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus the input</button>
    </div>
  );
}

export default FocusInput;

useMemo

概要

重い計算の結果をメモ化し、依存関係が変わったときだけ再計算するためのHookです。パフォーマンスの最適化に使います。

使い方

JSX
const memoizedValue = useMemo(() => create, [dependencies]);

使用例

JSX
import React, { useState, useMemo } from 'react';

function ExpensiveCalculationComponent() {
  const [count, setCount] = useState(0);
  const [inputValue, setInputValue] = useState('');

  const expensiveCalculation = (num) => {
    console.log('Expensive calculation...');
    for (let i = 0; i < 1000000000; i++) {} // 重い処理のシミュレーション
    return num * 2;
  };

  const memoizedValue = useMemo(() => expensiveCalculation(count), [count]);

  return (
    <div>
      <input 
        type="text" 
        value={inputValue} 
        onChange={(e) => setInputValue(e.target.value)} 
      />
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <p>Expensive Calculation Result: {memoizedValue}</p>
    </div>
  );
}

export default ExpensiveCalculationComponent;

useCallback

概要

依存関係が変わったときだけ新しい関数を作成するためのHookです。特に、子コンポーネントに関数を渡すときの不要な再レンダリングを防ぐのに役立ちます。

構文

JSX
const memoizedCallback = useCallback(() => {
  // 関数の内容
}, [dependencies]);

使用例

JSX
import React, { useState, useCallback } from 'react';

function ParentComponent() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

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

  return (
    <div>
      <ChildComponent onIncrement={increment} />
      <p>Count: {count}</p>
      <input 
        type="text" 
        value={text} 
        onChange={(e) => setText(e.target.value)} 
        placeholder="Type something"
      />
    </div>
  );
}

function ChildComponent({ onIncrement }) {
  console.log('ChildComponent rendered');
  return (
    <button onClick={onIncrement}>Increment</button>
  );
}

export default ParentComponent;

Custom Hook

概要

複数のHookを組み合わせて再利用可能なロジックを作成するためのカスタムHookです。
useで始まる名前を使うことで、他のReactコンポーネントでも使える便利な関数を作れます。

構文

JSX
function useCustomHook() {
  // フックのロジック
  return someValue;
}

使用例

ウィンドウのサイズを追跡するカスタムHook

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

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }

    window.addEventListener('resize', handleResize);
    
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowSize;
}

export default useWindowSize;

呼び出し方法

JSX
import React from 'react';
import useWindowSize from './useWindowSize';

function MyComponent() {
  const { width, height } = useWindowSize();

  return (
    <div>
      <p>Width: {width}px</p>
      <p>Height: {height}px</p>
    </div>
  );
}

export default MyComponent;

コメント

タイトルとURLをコピーしました