DEV Community

Origami
Origami

Posted on • Edited on

2 1

custom hooksをグローバル変数みたいに扱わないで

english: https://dev.to/origamium/don-t-use-custom-hooks-like-global-state-dda

はい、まずこのコードを見てください。


const useInvalidHooks = () => {
  const [state, setState] = useState(false);
  const handler = useCallback(() => {
    setState(true);
  }, []);

  return [state, handler];
};

export default function ParentComponent() {
  const [state] = useInvalidHooks();
  console.log(`parent: ${state}`);
  return (
    <div>
      <InnerComponent />
    </div>
  );
}

function InnerComponent() {
  const [state, handler] = useInvalidHooks();
  console.log(`children: ${state}`);
  return <button onClick={handler}>hai</button>;
}

Enter fullscreen mode Exit fullscreen mode

このとき、InnerComponetのbuttonを押下したさい、その親であるParentComponentstateの変更と更新を期待していると、ものの見事に打ちのめされます。変更されません。
経験豊かなReactエンジニアにはその理由はすぐわかると思います。

はい、理由は生成されたhooksは他のhooksの状態とは完全に別ですからです。私はこれに2時間ぐらい悩みましたが…

Top comments (1)

Collapse
 
dance2die profile image
Sung M. Kim

Note: I read the translated version.

Yes, hooks don't share states in different components. That used to get me too.

Image of DataStax

AI Agents Made Easy with Langflow

Connect models, vector stores, memory and other AI building blocks with the click of a button to build and deploy AI-powered agents.

Get started for free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay