---
title: "The dangers of using objects in ReactJS useState and useEffect hooks."
description: "Learn the pitfalls of using objects with useState and useEffect in ReactJS. Solve state update issues using shallow copies, useReducer, or immutable.js."
url: "https://significa.co/blog/dangers-of-using-objects-in-usestate-useeffect-reactjs-hooks"
datePublished: "2023-02-01T22:05:00.000Z"
dateModified: "2025-02-27T11:34:41.860Z"
---

1 Feb 2023 · Updated 27 Feb 2025 · 3 min read

# Dangers of using Objects in useState and useEffect ReactJS Hooks.

[Development](https://significa.co/blog?t=Development)

In this article, we explore a problem/bug that can easily go unnoticed when using objects with hooks.

![Dangers of using objects in useState illustration cover.](https://a.storyblok.com/f/198185/3840x1920/57348f0164/dangers-or-using-objects-in-usestate.png/m/1440x0/)

Hooks have been around for a few years now. They were added in [React v16.8.0](https://github.com/facebook/react/blob/master/CHANGELOG.md#1680-february-6-2019), and let you use state and other React features without writing a class.

In this article, we won't be going into much detail about what a hook is, its syntax, and so on. For that, you can visit the React [documentation page](https://reactjs.org/docs/hooks-intro.html) where we think that the React team did a great job explaining it.

---

## (Un)known problem of using objects in useState/useEffect hooks

What brings us here is a problem/bug we faced when we first started using hooks that can easily go unnoticed.

Let's look at the following example:

```typescript
const { useState } = React

const Counter = () => {
  const [count, setCount] = useState(0)
  const [objectCount, setObjectCount] = useState({ count: 0 })

  return (
    <div>
      <h2>Count</h2>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Increase normal count</button>

      <h2>Object Count</h2>
      <p>You clicked {objectCount.count} times</p>
      <button
        onClick={() => {
          objectCount.count += 1
          setObjectCount(objectCount)
        }}
      >
        Broken increase of the object count
      </button>

      <button
        onClick={() =>
          setObjectCount({
            ...objectCount,
            count: objectCount.count + 1,
          })
        }
      >
        Functioning increase of the object count
      </button>
    </div>
  )
}

ReactDOM.render(<Counter />, document.getElementById('app'))
```

We prepared [this codepen](https://codepen.io/tmpduarte/pen/yLJWdwm) with the example, feel free to visit and play around with it.

In our example, we have:

- A `count` state hook that stores a plain number;
- An `objectCount` state hook that stores an object that contains the `count` property inside;
- An _Increase normal count_ button that updates the `count` state. You can validate this by seeing that the counter updates right after pressing the button.
- A _Broken increase of the object count_ button that tries to update the `objectCount`, but fails miserably. You might be thinking, _“Naah, that should work…"._ Go ahead and try it out on [codepen](https://codepen.io/tmpduarte/pen/yLJWdwm) [.](https://codepen.io/tmpduarte/pen/yLJWdwm)
- A _Functioning increase of the object count_ button that properly updates the `objectCount` state.

---

## **Why does pressing the** **_Broken increase of the object count_** **button doesn't immediately increase the object count?**

When a user presses the button, we increase the `count` property inside the `objectCount` object and then call `setObjectCount(objectCount)`.

The problem with this is that the `useState` hook uses [strict equality comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) to determine if it should trigger a re-render and doesn't check if the properties of the object actually changed.

In other words, the hook compares (`===`) the "old" and "new" states and concludes that the object hasn't changed and won't trigger a re-render, causing the object count label to stay the same.

---

## Possible solutions

### **Create and pass a shallow copy to** `setObjectCount`

The _Functioning increase of the object count_ button fixes the issue by creating and passing a shallow copy of the `objectCount` to the setter function.

It basically keeps the same object properties but creates a new object reference so that the hook strict equality comparison determines that the state changes, and immediately triggers a re-render.

### **Create and pass a shallow copy to** `setObjectCount`

Another solution would be to simply not use objects in an `useState` hook.

You could use the `useState` hook per each property of the object. In theory, this would be the ideal scenario, but doing this might be daunting and time-consuming.

You might have your reasons to directly store an object as state. In our case, we were retrieving data from an API and decided to store the object retrieved.

### **Use the** [**useReducer**](https://reactjs.org/docs/hooks-reference.html#usereducer) **hook**

If you are familiar with Redux you already know how this works as it is very similar.

`useReducer` accepts a reducer of type `(state, action) => newState`, and returns the current state paired with a `dispatch` method.

This is usually preferable to `useState` when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

### **Use** [**immutable.js**](https://immutable-js.github.io/immutable-js/)

As per the documentation, "[Immutable](http://en.wikipedia.org/wiki/Immutable_object) data cannot be changed once created, leading to much simpler application development, no defensive copying, and enabling advanced memoization and change detection techniques with simple logic. Persistent data presents a mutative API which does not update the data in-place, but instead always yields newly updated data."

In practical terms, when using immutable.js, every object change would actually create a new object. In our example, this would cause the state hook to trigger a re-render.

Keep in mind that the same problem and solutions apply to the (optional) list of dependencies of the [useEffect](https://reactjs.org/docs/hooks-effect.html) hook.

### Time saver

When this problem happened to me and [Rui Sousa](https://significa.co/about/rui-sousa), we spent, I would say, a couple of hours hunting down the problem. So we felt like sharing this tip in hopes that it saves you debug time.

If you have a suggestion or a different solution than the ones listed, go ahead and drop us a message.

### Find expert assistance

If you are having trouble figuring out how to solve this, you should hire a [React JS developer](https://www.toptal.com/react) to manage complex states in React applications.

---

## References

- [Hooks at a Glance](https://reactjs.org/docs/hooks-overview.html)
- [Using the State Hook](https://reactjs.org/docs/hooks-state.html)
- [Using the Effect Hook](https://reactjs.org/docs/hooks-effect.html)
- [MDN – Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness)
- [Understanding Deep and Shallow Copy in JavaScript](https://medium.com/@manjuladube/understanding-deep-and-shallow-copy-in-javascript-13438bad941c)

Tiago Duarte

CPO

[Author page](https://significa.co/about/tiago-duarte)

Tiago has been there, seen it, done it. If he hasn’t, he’s probably read about it. You’ll be struck by his calm demeanour, but luckily for us, that’s probably because whatever you approach him with, he’s already got a solution for it. Tiago is the CPO at Significa.
