4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

カスタムフックはstate自体ではなく、stateを使うロジックを共有する

4
Last updated at Posted at 2025-09-19

はじめに

個人開発でカスタムフックを使う際に少し悩んだので記事にします。タイトルはReactの公式ドキュメントから取ってきたものです。

問題

以下のようにComponent1で更新したstateをuseCustomHook2のロジックで使おうとしたのですが、なぜか空配列になってしまう。(そもそもカスタムフックからカスタムフックを呼んでるのは渋いかもです)

page.jsx
export const page = () => {
  const { data, setData } = useCustomHook1();
  const { ... }  = useCustomHook2(); 
  
  // Component1でsetData(data)すると値が入る
  console.log(data);
  return (
      <>
        <Component1 data={data} setData={setData} />
      </>
  )
};
useCustomHook2.js
export const useCustomHook2 = () => {
  const { data } = useCustomHook1();
  // Component1でsetData(data)しても空のまま
  console.log(data);
  return { ... };
};

原因と解決策

別の箇所で呼び出しているカスタムフックのstateは独立しており、状態を共有しているわけではないみたいです。Reactの公式ドキュメントにも書かれていました。

今回は要件的にカスタムフックの引数に対して直接値を渡してあげる形で対応しました。contextなどで状態管理することもできそうです。

おわりに

書きながら、考えたらそれはそうだよなと思いましたが一応記事にしました。

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?