Glenn
Glenn

Reputation: 5051

React useEffect: is it possible to set dependencies with a variable?

I'm calling a function to determine if a set of form fields are valid. I have a set of state variables that should trigger useEffect() but apparently I can't make an array beforehand like this without getting a warning:

const states = [name, email, password]

useEffect(() => {
  someFunction({ states })
}, states)

Instead I have to do this:

useEffect(() => {
  someFunction({ states: [name, email, password] })
}, [name, email, password])

This is annoying because I plan on using this pattern on other forms that will have 10-20 fields, so I hate to clutter it up by building that whole array every time. Is there a better way?

Upvotes: 1

Views: 932

Answers (1)

Iván
Iván

Reputation: 1060

Technically, yes, it's possible. What you're seeing is a warning from eslint, and you can disable it in a line/file basis. Check the docs here: https://eslint.org/docs/user-guide/configuring/rules#disabling-rules

const states = [name, email, password]

useEffect(() => {
  someFunction({ states })
}, states) // eslint-disable-line <eslint-error-id>

It's rarely a good idea to have a variable like that, as eslint won't be able to tell you if you're missing a dependency.

Upvotes: 2

Related Questions