Opinionated React: State Management

You don’t need to use a 3rd party library to manage state in your React application

faraz amiruddin
Better Programming

--

Opinionated React — State Management — Faraz Ahmad

Intro

I’ve been working with React for over four years. During this time, I’ve formed some opinions on how I think applications should be. This is part three in a series of opinion pieces on this topic.

What I’ll Be Covering

There are a lot of parts to state management. I won’t be able to cover them all in one sitting. For this post, I’ll show you how I use plain React to manage state in my components.

Make sure to follow me for my future posts related to state management, where I’ll write about:

  • Component level state vs global state
  • Good use cases and my pattern for React context
  • Status enums instead of booleans

Just Use React

All too often have I seen teams adopt state management libraries like Redux, MobX, or something else before using React’s built-in state management solution.

There’s nothing wrong with these libraries, but they’re not necessary to build a fully functioning React application. In my experience, it’s significantly easier to use plain React.

If you think you have a good reason to use one of these libraries instead of using useState or useReducer, please leave a comment because I would love to know your use case.

Next time you build a component, try using plain React.

Hooks

I mentioned two hooks above: useState and useReducer. Here’s how I use each of them.

Start with useState

I start by building my components with the useState hook. It’s quick and gets the job done:

useState to render a list of movies.

If we need another piece of state, simply add another useState hook:

add another useState to display an isLoading state

useReducer when you have a lot of state

My limit for related pieces of state is two. If I have three pieces of state that are related to each other, I opt for useReducer.

Following the above example, let’s say we wanted to display an error message if fetching the movies failed.

We could add another useState call, but I think it looks a bit messy:

Too many set calls

Let’s refactor this to use useReducer, which will simplify our logic:

useReducer when we have more than two pieces of state

Q&A

In every article I answer a question I received on Twitter. Here’s this week’s question:

Wrapping Up

This is the third installment in a series of pieces I’m writing. If you enjoyed this, please comment below. What else would you like me to cover? As always, I’m open to feedback and recommendations.

Thanks for reading.

P.S. If you haven’t already, be sure to check out my previous posts in this series:

1. An Opinionated Guide to React: Folder Structure and File Naming
2. An Opinionated Guide to React: Component File Structure

--

--