'Set a condition inside React useState hook

I have this code:

const [o, setO] = useState(data === 'test' ? {name: "bill", age: 3} : {});

Is the statement above valid or should I use useEffect:

useEffect(() => {
  if (data === 'test') {
    setO(myObj)
  } else {
    setO({})
}, []);

Which is better? If the first one is correct does setting condition inside useState have a side effect or not?



Solution 1:[1]

Go for useEffect. As it will set the state after mounting ui. By setting state in useState there will be effect until you setState to change your state

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RoshaanAli