DEV Community

chaoui-del-gado
chaoui-del-gado

Posted on

ugly useState

Hi, in React

const [rabbits, setRabbits] = useState();
Enter fullscreen mode Exit fullscreen mode

We can't setRabbits() inside "if", "for", etc.
Indeed, tried and doesn't work.

So I use it this way :

let rabbitsCloned = structuredClone(rabbits);
if (.....) {
   rabbitsCloned[5] = "this rabbit has changed"
}
setRabbits(rabbitsCloned)
Enter fullscreen mode Exit fullscreen mode

It works. If the condition is fullfilled or not, the state is set well.

But this is ugly I guess.

How can we best set state with all the logic implying conditions and loops ?

Merci beaucoup !
Chaw

Top comments (0)