Borislav Hadzhiev
Wed Apr 27 2022·2 min read
Photo by Ryan Jvr
To remove a key from a state object in React:
useState
hook to store the state object.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> ); }
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.
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.
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.