メインコンテンツへスキップ
ブログ一覧に戻る
フロントエンド開発

React Hooksの実践的な使い方と自作Hooksの設計

2023年11月20日
7分で読めます
React Hooksの実践的な使い方と自作Hooksの設計

この記事の結論

Reactの各種Hooksを使いこなすコツと、再利用可能な自作Hooksを設計するためのベストプラクティスを紹介します。

React Hooksの実践的な使い方と自作Hooksの設計

Reactの各種Hooksを使いこなすコツと、再利用可能な自作Hooksを設計するためのベストプラクティスを紹介します。

はじめに

React Hooksは、関数コンポーネントで状態管理やライフサイクルを扱うためのAPIです。本記事では、主要なHooksの使い方と、再利用可能なカスタムHooksの設計方法を解説します。

主要なHooks

useState

状態を管理するためのHookです:

import { useState } from 'react'

function Counter() {
  const [count, setCount] = useState(0)
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  )
}

useEffect

副作用を処理するためのHookです:

import { useEffect, useState } from 'react'

function DataFetcher() {
  const [data, setData] = useState(null)
  
  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(setData)
  }, [])
  
  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>
}

カスタムHooksの設計

useFetch Hook

データフェッチングを抽象化したカスタムHook:

import { useState, useEffect } from 'react'

function useFetch<T>(url: string) {
  const [data, setData] = useState<T | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)
  
  useEffect(() => {
    setLoading(true)
    fetch(url)
      .then(res => res.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false))
  }, [url])
  
  return { data, loading, error }
}

useLocalStorage Hook

ローカルストレージを扱うカスタムHook:

function useLocalStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key)
      return item ? JSON.parse(item) : initialValue
    } catch (error) {
      return initialValue
    }
  })
  
  const setValue = (value: T | ((val: T) => T)) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value
      setStoredValue(valueToStore)
      window.localStorage.setItem(key, JSON.stringify(valueToStore))
    } catch (error) {
      console.error(error)
    }
  }
  
  return [storedValue, setValue] as const
}

React Hooks・カスタムHooks設計の要点

React Hooksを適切に使用し、カスタムHooksを設計することで、コードの再利用性と保守性を向上させることができます。

関連記事


ご相談・お問い合わせはこちら

次の一手

状況に合わせて、選んでください。