orizo-ono / step-up-react-sec12

chakraUIでの実装
1 stars 0 forks source link

`useCallBack`を使う上での注意点 #11

Open orizo-ono opened 1 year ago

orizo-ono commented 1 year ago

まずは下記コード


import axios from "axios";
import { useCallback, useState } from "react";
import { User } from "../types/api/user";
import { useMessage } from "./useMessage";

export const useAllUsers = () => {
  const [ loading, setLoading ] = useState( false );
  const [ users, setUsers ] = useState<Array<User>>( [] );
  const { showMessage } = useMessage();

  const getUsers = useCallback( () => {
    setLoading( true );
    axios.get<Array<User>>( 'https://jsonplaceholder.typicode.com/users' )
      .then( ( res ) => setUsers( res.data ) )
      .catch( () => showMessage( { title: "ユーザーの取得に失敗しました", status: "error" } ) )
      .finally( () => { setLoading( false ); } );
  }, [] );

  return { getUsers, users, loading };
};

[eslint] 
src/hooks/useAllUsers.ts
  Line 19:6:  React Hook useCallback has a missing dependency: 'showMessage'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

WARNING in [eslint] 
src/hooks/useAllUsers.ts
  Line 19:6:  React Hook useCallback has a missing dependency: 'showMessage'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

webpack compiled with 1 warning
No issues found.

結論

依存配列の中には、使用する関数引数``propsを入れなければならない 意図しない無限ループが発生してしまう。