🚀

react native custom hook例

2024/03/21に公開

react のcustom hooksを使った例

基本

  • state
  • 処理
    • useEffect
  • state, 処理方法を返す

感じ

  • counter

    以下は、React Native Custom Hooksを使った例です。ここでは、useCounterというCustom Hookを定義し、それを使用したCounterコンポーネントを作成します。

    src/hooks/useCounter.js

    import { useState } from 'react';
    
    export function useCounter(initialCount = 0) {
      const [count, setCount] = useState(initialCount);
    
      const increment = () => setCount(prevCount => prevCount + 1);
      const decrement = () => setCount(prevCount => prevCount - 1);
      const reset = () => setCount(initialCount);
    
      return { count, increment, decrement, reset };
    }
    

    src/components/Counter.js

    import React from 'react';
    import { View, Text, Button } from 'react-native';
    import { useCounter } from '../hooks/useCounter';
    
    export function Counter() {
      const { count, increment, decrement, reset } = useCounter(0);
    
      return (
        <View>
          <Text>Count: {count}</Text>
          <Button title="Increment" onPress={increment} />
          <Button title="Decrement" onPress={decrement} />
          <Button title="Reset" onPress={reset} />
        </View>
      );
    }
    

    この例では、以下のような構成になっています:

    1. useCounterというCustom Hookを定義しています。このHookは、カウンターの状態(count)と、その状態を操作するための関数(incrementdecrementreset)を提供します。
    2. Counterコンポーネントは、useCounter Hookを使用しています。useCounterから返されるcount状態と関数を使って、カウンターのUIを構築しています。
    3. Appコンポーネントは、Counterコンポーネントをレンダリングしています。

    このように、Custom Hookを使用することで、カウンターのロジックを再利用可能な形で抽出し、コンポーネントのコードを簡潔に保つことができます。

    実際のアプリケーションでは、より複雑な状態管理やAPIリクエストなどのロジックをCustom Hookに移動することで、コンポーネントの関心事を分離し、コードの保守性を向上させることができます。

    このようなCustom Hookの使用方法は、React NativeとReactで共通です。React Nativeの場合は、react-nativeから必要なコンポーネント(ViewTextButtonなど)をインポートして使用します。

    Custom Hookを活用することで、React Nativeアプリケーションの開発を効率化し、コードの再利用性と保守性を高めることができます。

  • fetchData

    ここでは、useFetchDataというCustom Hookを定義し、それを使用したUserListコンポーネントを作成します。

    src/hooks/useFetchData.js

    import { useState, useEffect } from 'react';
    
    export function useFetchData(url) {
      const [data, setData] = useState(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
    
      useEffect(() => {
        fetchData();
      }, []);
    
      const fetchData = async () => {
        try {
          const response = await fetch(url);
          const json = await response.json();
          setData(json);
          setLoading(false);
        } catch (error) {
          setError(error);
          setLoading(false);
        }
      };
    
      return { data, loading, error };
    }
    

    src/components/UserList.js

    import React from 'react';
    import { View, Text, FlatList, ActivityIndicator } from 'react-native';
    import { useFetchData } from '../hooks/useFetchData';
    
    export function UserList() {
      const { data, loading, error } = useFetchData('https://api.example.com/users');
    
      if (loading) {
        return <ActivityIndicator size="large" />;
      }
    
      if (error) {
        return <Text>Error: {error.message}</Text>;
      }
    
      return (
        <FlatList
          data={data}
          keyExtractor={(item) => item.id.toString()}
          renderItem={({ item }) => (
            <View>
              <Text>{item.name}</Text>
              <Text>{item.email}</Text>
            </View>
          )}
        />
      );
    }
    

Discussion