Skip to content

Bug: eslint-plugin-react-hooks cannot use optional chaining in deps #18819

Closed
@coolkev

Description

@coolkev

React version: 16.3.1
eslint-plugin-react-hooks version: 4.0.0

Steps To Reproduce

Use ?. in dependency to any of the react hooks.

export default function App() {
    const x = Date.now() % 2 === 0 ? { test: true } : undefined;
  
    React.useEffect(() => {
      if (x?.test) {
        console.log('test');
      }
    }, [x?.test]);
  
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
      </div>
    );
  }
  

Link to code example:
I was unable to reproduce the behavior in codesandbox, it must be transforming the code or stripping out the ? before linting. It happens in VS Code.

The current behavior

eslint errors occur:
React Hook React.useEffect has a missing dependency: 'x'. Either include it or remove the dependency array.eslintreact-hooks/exhaustive-deps
React Hook React.useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked.eslintreact-hooks/exhaustive-deps
image

The expected behavior

I would expect it to work just like it does currently for non-optional child member access.
image
When ? is removed, it no longer shows eslint errors, but obviously would fail at runtime if x is undefined.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions