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)