Skip to content

· 2 min read

Why useState is out of date

Also on Medium

A few weeks ago, I wrote a post criticizing useState, which you can read more about here. Now, I have a new perspective on why useState will eventually become a hook that we stop using.

You may ask why we use useState in the first place. Well, it’s a way to add state to a React component, which means we can define a variable and have our component “change” to it when it updates or re-renders, as we call it in React. Take this counter component, for example:

The counter component is simple, defining a state variable counter that changes every time we click the "increase" button. It's a small piece of code, so the performance issue with every update re-rendering the entire component isn't noticeable. But imagine if we had larger components with multiple variables defined like the message variable I mentioned earlier. Every time the counter changes, the message variable gets redefined, which can lead to performance issues we want to avoid.

useSignal: Our hero

This is where useSignal comes in. useSignal is a hook from Qwik, which you may have heard of from Preact. To put it briefly, useSignal is similar to useState but with a more focused approach. Let me explain.

useSignal takes advantage of something I really like — in order to get and set a new value of count, you access it the same way using the value property of the signal. Since useSignal also takes advantage of reactivity, it only changes the parts of the component where count.value is being read.

Here’s an image from the creator of qwik, which he uses to compare code using useState and useSignal (you can follow him on Twitter @mhevery).

Both examples are similar to the one above. As you can see, on the right side, every time setCount is executed, the whole component re-renders. On the left side, it only changes where we use the count.value. This is a clean and fast solution.

In conclusion, I hope that at some point in the future, we will have a native implementation of useSignals in React. It’s an extremely powerful and useful tool for cases where you want to keep your code clean and have a component that performs well over time.

thanks for reading me and happy coding :)