CodeRocks
CodeRocks

Reputation: 715

useEffect as Callback for useState has too many dependencies

I am re-writing a class component with React Hooks (because it's cleaner) but am facing an issue. In my class component I have a callback function to this.setState({B: "blah blah blah"}, () => {//do some function with state A}), so that every time state x changed, I would use the new state value in conjunction with State B. When I try to implement the same functionality with React Hooks like so:

useEffect(() => {
    // Use state A with state B in function
   myFunction();
}, [myFunction])

const myFunction = useCallback(() => {console.log(`${A} and ${B}`}, [A, B]);

I only want my function to run when state A changes -- not state B...however right now it re-renders any time state A or state B renders.

I've tried only including one dependency -- A -- in the useCallback [A] -- but the problem is then I get: React Hook useCallback has a missing dependency: 'B'. Either include it or remove the dependency array

Upvotes: 0

Views: 915

Answers (3)

Caio Henrique
Caio Henrique

Reputation: 98

useEffect is composed by two params

effect: A imperative function that can return a cleanup function;

deps: If present, effect will only activate if the values in the list change.

Got this information on Visual Studio Code tips

So if you want to activate the effect only when "A" changes, you should put "A" on deps.

useEffect(() => {}, [A]);

Upvotes: 0

Marco Mesen
Marco Mesen

Reputation: 675

useState allows you send a function into its params, like a cb, always this cb needs to return a new state to render Example:

setState((state) => {
    /** 'state' in this moment represent the state without changes */
    /** You can do all that you need with 'state' */
    console.log(state)
    /** */
    return (newState)
  })

useEffect dont has any functions in this moment, y useCallback is not necesary

If you have a handleChange function, i can give you a example if your state contains personal data:

const [person, setPerson] useState({name: '', lastName: ''})

const handleChange = (newPerson) => {
  setPerson((person) => {
    /** 'person' in this moment represent the state without changes */
    /** You can do all that you need with 'person' */
    console.log(person)
    /** */
    return (newPerson)
  })
}

Upvotes: 0

O.Cuenca
O.Cuenca

Reputation: 151

Maybe try using

}, [A])

as the only dependency and at the end of the function use a comment like this :

// eslint-disable-next-line 

That will disable the missing dependency and give you the result that you want. That usually works for me.

Upvotes: 2

Related Questions