Advanced React Hacks 1/10 - Conditional Hooks
According to react.dev "Rules of Hooks" you cannot call hooks inside a condition
https://react.dev/warnings/invalid-hook-call-warning#breaking-rules-of-hooks
But what if you want it?
Use components!
export const ParentComponent = ({ component }: ParentComponentProps) => {
/* derive condition here */
// const condition = false;
const condition = true;
/* derive property here */
// cont property = 0;
// ...
return (<>
{
condition && <HookComponent hookProperty={property} />
}
</>);
}
export const HookComponent = ({ hookProperty }: ChildComponentProps) => {
useCustomHook(hookProperty); // could be anything!
return <></>; // yes, components can render nothing
}
With great power comes great responsibility!
Hope this helps! More next time...
No comments:
Post a Comment