How to check if an Object is Empty in React

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

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

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

An alternative approach is to try to iterate over the properties of the object. If there is even a single iteration, then the object is not empty.

App.js
function isEmpty(obj) { for (const property in obj) { return false; } return true; } console.log(isEmpty({})); // 👉️ true console.log(isEmpty({id: 1, name: 'Alice'})); // 👉️ false

If there is even 1 iteration, we know that the object has at least 1 key-value pair and is not an empty object.

If there aren't any iterations, then the object is empty.

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.