Don't use custom hooks as like global state
Origami
Posted on January 24, 2020
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...
đź’– đź’Ş đź™… đźš©
Origami
Posted on January 24, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.