The Bane of Immutable React State

Avery Duffin
2 min readMay 5, 2020

React state may not always be immutable

Photo by DDP on Unsplash

Today I was working through a problem with a component involving the react context API which was holding state I was sharing between two components. Testing out my knowledge of hooks I decided to useReducer and wrap my context API in a hook. Here’s an article I used to get started.

After happily coding away I was up and running. A beautiful new react hook that held all the state I needed to share between these components.

Well little did I realize but I had set myself up for failure before anything had begun.

The bain of all my react and state management life: objects nested in other objects.

In this article I'm not going to describe how to set up a react reducer hook with context API's Ill let other much more intelligent people do that. I will just describe the problem and one way to fix it.

Problem

In many places in react you can kill yourself by passing objects of objects to your functions.

The reason for this is because the nested object isn’t being passed by value as we would hope. It's being passed by reference.

This can be especially troublesome when you are working with state in react.

--

--

Avery Duffin

Im a software engineer, react developer, inventor, salesman, family man, religious, and outdoor connoisseur