Home > Mobile >  useEffect warning while setState is used inside it
useEffect warning while setState is used inside it

Time:01-16

here is the code inside useEffect in component, I want to update these states after the first render. I want to obtain my goal without dependencies warning.

useEffect(() => {
    setQualification({ ...qualification, options: handleOptionToData("Qualification") })
    setWorkingWith({ ...workingWith, options: handleOptionToData("Working with") })
    setAnnualIncome({ ...annualIncome, options: handleOptionToData("Income") })
    setProfessionArea({ ...professionArea, options: handleOptionToData("Profession area") })
    setOptionsData(true)
}, [])

and for that i got these warning:

React Hook useEffect has missing dependencies: 'annualIncome', 'handleOptionToData', 'professionArea', 'qualification', and 'workingWith'. Either include them or remove the dependency array. You can also do a functional update 'setWorkingWith(w => ...)' if you only need 'workingWith' in the 'setWorkingWith' call react-hooks/exhaustive-deps

CodePudding user response:

Add the dependency on dependencies array like this

const [data , setData] = useState({ 
 qualification : {},
 workingWith : {},
 annualIncome : {},
 professionArea : {}
})

useEffect(() => {
    const newData = {
     ...data,
     qualification : { ...data.qualification , options: handleOptionToData("Qualification") },
     workingWith : { ...data.workingWith , options: handleOptionToData("workingWith") },
     annualIncome : { ...data.annualIncome , options: handleOptionToData("annualIncome") },
     professionArea : { ...data.professionArea , options: handleOptionToData("Profession area") },
    }

    setData(newData)
    setOptionsData(true)
}, [qualification, workingWith , annualIncome , professionArea])

CodePudding user response:

You can use this syntax to avoid dependency on the state,

useEffect(()=>{
  setState(prev=>*your logic*)
},[setState])

This way you can use prev to update new state and your state will no longer be a dependency of the useEffect and will not cause an infinite loop.

  •  Tags:  
  • Related