Better Programming

Advice for programmers.

Follow publication

Member-only story

Why React’s useState Isn’t a Good Solution for Derived Values

Bikash Paneru
Better Programming
Published in
4 min readApr 13, 2021

computer code on a screen
Image by Ferenc Almasi in Unsplash

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 and selectedHexes, and onColorClicked as props.
  • This component displays all colors that lie between startHex and endHex. 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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Bikash Paneru
Bikash Paneru

Written by Bikash Paneru

Technology for Passion, Noodles for Hair and Junk for Food. https://mrdivinemaniac.github.io/

Responses (2)

Write a response

nice click bait title ;)

--

Seems like generating the entire list once and then just rendering using a filter on the array to only include the colors in range would be a better approach. You’d only generating the list once. You could also just increment within the color component and handle everything with one pass.

--