Conditional hooks issue
Hooks are auto fixed and added creating below issue
React Hook "useMemo" 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? eslint(react-hooks/rules-of-hooks)
This is not just eslint warning, such hooks crash React application if missed to fix and trust auto fix feature Is it possible to detect conditional state of memoized elements and not fix them?
Could you please provide an example?
so it's one of below codes returned as render result
return <div>
{condition1 ?
<span>1</span>
:
<span prop1={useMemo(() => value1, [])}>2</span>
}
</div>
or
return <span prop1={condition1 ? useMemo(() => value1, []) : 1}>1</span>
or
if (condition) {
return <span>1</span>
}
const value1 = useMemo(() => prop1, []);
return <span>{value1}</span>
@blackswanny,
I’ve just come back to this and can’t get the auto-fixer to generate this conditional inline useMemo. Can you verify if this still happens? If so, please provide a full file with a code that reproduces the error instead of the resulting, broken, auto-fixed code. Also include the options for the rule that are being used.
I am also seeing this problem. For example:
<MyComponent
data={ props?.data || {} }
/>
Upon save in VSCode with "Editor: Format on Save" enabled, this results in the following adjustment.
<MyComponent
data={ props?.data || useMemo(() => ({}), []) }
/>
Barring the questionable nature of the original code, the resulting auto-fix obviously can't work. The fixing seems really naive but I wouldn't be surprised if that is an unavoidable problem. It does make working in files that has code like this nearly impossible with this eslint plugin and auto-fix on save enabled.
Would be nice to have an option to never generate inline hooks like this.