I have a component that needs to call a custom React hook only when certain prop is passed. Like this:
import { useCustomHook } from './myHook';
export function Chart(props) {
...
{lots of code here}
...
if (props.canTrack) {
useCustomHook();
}
return <SomeComponent options={props.option} />
}
This is complaining with:
error React Hook "useCustomHook" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?
I was able to quickly go around this by duplicating the Chart component into 2 Components:
import { useCustomHook } from './myHook';
export function Chart(props) {
...
{lots of code here}
...
return <SomeComponent options={props.option} />
}
export function TrackedChart(props) {
...
{lots of code here}
...
useCustomHook();
return <SomeComponent options={props.option} />
}
Which works but now I got duplicated code which is highly undesirable. In an OOP language I could use inheritance, what is the correct approach in React to avoid duplicating code or even better, be able to safely call hooks conditionally.