Remove a Key from a state Object in React

avatar

Borislav Hadzhiev

Last updated: Apr 27, 2022

banner

Photo from Unsplash

Remove a Key from a state Object in React #

To remove a key from a state object in React:

  1. Use the useState hook to store the state object.
  2. Destructure the key of the object and the rest of the properties.
  3. Set the state to the rest of the properties.
App.js
import {useState} from 'react'; export default function App() { const initialState = { id: 1, name: 'Alice', salary: 100, department: 'development', }; const [employee, setEmployee] = useState(initialState); const removeKey = () => { setEmployee(current => { // 👇️ remove salary key from object const {salary, ...rest} = current; return rest; }); }; return ( <div> <button onClick={removeKey}>Click</button> <h4>{JSON.stringify(employee, null, 4)}</h4> <hr /> <h2>name: {employee.name}</h2> <h2>department: {employee.department}</h2> <h2>salary: {employee.salary}</h2> </div> ); }

remove key from state object

To remove a key from a state object, we destructured the key and the rest of the properties and updated the state to the rest of the properties.

Alternatively, you can use the delete operator.

App.js
import {useState} from 'react'; export default function App() { const initialState = { id: 1, name: 'Alice', salary: 100, department: 'development', }; const [employee, setEmployee] = useState(initialState); const removeKey = () => { setEmployee(current => { // 👇️ create copy of state object const copy = {...current}; // 👇️ remove salary key from object delete copy['salary']; return copy; }); }; return ( <div> <button onClick={removeKey}>Click</button> <h4>{JSON.stringify(employee, null, 4)}</h4> <hr /> <h2>name: {employee.name}</h2> <h2>department: {employee.department}</h2> <h2>salary: {employee.salary}</h2> </div> ); }

If you decide to use the delete operator, make sure to create a copy of the state object using the spread syntax (...).

We used the spread syntax (...) to unpack the key-value pairs of the object into a new object and create a shallow copy.

We should never mutate state objects or arrays in React.

We passed a function to setState, because the function is guaranteed to be invoked with the current (most up to date) state.

App.js
const removeKey = () => { setEmployee(current => { // 👇️ create copy of state object const copy = {...current}; // 👇️ remove salary key from object delete copy['salary']; return copy; }); };

When the next state is computed using the previous state, pass a function to setState.

Otherwise, we might get some weird race condition if the state object we have access to does not represent the most up to date value.

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.