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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

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

Okay