简体   繁体   中英

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

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.

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)
  })
}

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM