DEV Community

Origami
Origami

Posted on • Edited on

3 1

Don't use custom hooks as like global state

yes. look this.

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

Click button in InnerComponent. And if you think update ParentComponent const [state] = useInvalidHooks, its wrong.
This code is equivalent to the following code.

export default function ParentComponent() {
  const [state, setState] = useState(false);
  const handler = useCallback(() => {
    setState(true);
  }, []);

  console.log(`parent: ${state}`);
  return (
    <div>
      <InnerComponent />
    </div>
  );
}

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

  console.log(`children: ${state}`);
  return <button onClick={handler}>hai</button>;
}
Enter fullscreen mode Exit fullscreen mode

it's obvious.

custom hooks may misunderstanding: custom hooks is globally... isn't it.
custom hooks is locally.

If you need global state on custom hooks, use context api. or redux...

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

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

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

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

Okay