eslint-plugin-react-usememo icon indicating copy to clipboard operation
eslint-plugin-react-usememo copied to clipboard

Conditional hooks issue

Open blackswanny opened this issue 10 months ago • 5 comments

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?

blackswanny avatar Feb 20 '25 01:02 blackswanny

Could you please provide an example?

arthurgeron avatar Mar 13 '25 00:03 arthurgeron

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 avatar Mar 13 '25 20:03 blackswanny

@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.

arthurgeron avatar Apr 21 '25 01:04 arthurgeron

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.

Fargrim avatar Jun 03 '25 19:06 Fargrim

Would be nice to have an option to never generate inline hooks like this.

punkpeye avatar Aug 17 '25 22:08 punkpeye