Last updated: Apr 7, 2024
Reading timeยท2 min
To check if an object is empty in React:
Object.keys()
method to get an array of the object's keys.length
property on the array.length
of 0
, then the object is empty.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> ); }
We used the Object.keys() method to get an array of all of the object's keys.
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).
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.
<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.
useEffect
hookOnce the state object is updated, the useEffect
hook runs.
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]);
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.