Member-only story
Why React’s useState Isn’t a Good Solution for Derived Values
A common misuse of useState in React and a better solution
State is one of the fundamental concepts in React. The useState
hook is the foundation of state management in functional React components. In fact, most beginners start their React journey by learning about state management and the useState
hook.
However, when writing code, some things unfortunately get used in places where there are better alternatives. These often end up making code more complicated than it needs to be. Here we will look at a common misuse of the useState
hook and a better solution to the problem. This particular misuse is one that I have seen a lot of developers do and which I also used to do for a long time.
The Use Case
In order to study how we can better use and manage state, we are going to implement a use case. We will create a React component called ColorList
.
- The component takes
startHex
,endHex
andselectedHexes
, andonColorClicked
as props. - This component displays all colors that lie between
startHex
andendHex
. The list of colors must change if any of these properties change. - A user can select multiple colors from the list. The colors which are passed in the
selectedHexes
list are shown as selected.
Example: If startHex
is #FF0000
and endHex
is #FF0002
, the component will display the colors #FF0000
, #FF0001
, and #FF0002
.
We will not be implementing algorithms here but rather just be looking at things related to state management. So we will leave out implementation details for actually generating the hex values.
The Solution
We might come up with something like this as a trivial solution:
This obviously gets the job done. However, there is a problem with this component. This component will recalculate allHexes
every time it is re-rendered…