How to check if an Object is Empty in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Check if an Object is Empty in React

To check if an object is empty in React:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Access the length property on the array.
  3. If the array of keys has a length of 0, then the object is empty.
App.js
import {useEffect, useState} from 'react'; export default function App() { const [person, setPerson] = useState({}); useEffect(() => { if (Object.keys(person).length === 0) { console.log('Object is empty'); } if (Object.keys(person).length > 0) { console.log('Object is NOT empty'); } }, [person]); return ( <div> <h2>Object: {JSON.stringify(person)}</h2> <button onClick={() => setPerson({id: 1, name: 'Alice'})}> Set state </button> </div> ); }

react check if object is empty

The code for this article is available on GitHub

We used the Object.keys() method to get an array of all of the object's keys.

App.js
const obj = { id: 1, name: 'Alice', }; // ๐Ÿ‘‡๏ธ ['id', 'name'] console.log(Object.keys(obj)); const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // ๐Ÿ‘‰๏ธ false

The Object.keys method returns an empty array if the object has no key-value pairs (if it's empty).

App.js
const obj = {}; // ๐Ÿ‘‡๏ธ [] console.log(Object.keys(obj)); const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // ๐Ÿ‘‰๏ธ true

We set an onClick prop on the button element, so every time the button is clicked, a function is invoked.

App.js
<button onClick={() => setPerson({id: 1, name: 'Alice'})}> Set state </button>

The function sets the state object to a new value containing 2 properties.

I've also written an article on how to check if an array or a string is empty in React.

# Checking if an object is empty in the useEffect hook

Once the state object is updated, the useEffect hook runs.

App.js
useEffect(() => { if (Object.keys(person).length === 0) { console.log('Object is empty'); } if (Object.keys(person).length > 0) { console.log('Object is NOT empty'); } }, [person]);
The code for this article is available on GitHub

In our useEffect hook, we use the Object.keys() method to check if the object is empty.

If the length of the array that stores the object's keys is 0, then the object is empty, otherwise, the object contains at least 1 key-value pair.

If you need to remove a key from a state object, click on the link and follow the instructions.

I've also written an article on how to update nested properties in a state object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev