DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Origami
Origami

Posted on • Updated on

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>;
}

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>;
}

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...

Top comments (0)

๐ŸŒš Life is too short to browse without dark mode