Languages
[Edit]
EN

React - update object inside useState

0 points
Created by:
Dirask Community
5460

In this article, we would like to show you how to update property inside object returned by useState hook in React.

In order for React to register a change of state, we have to provide it a new object that has a different reference or a different value of a simple type.

We shouldn't call the setter directly in the component, we should execute it in any action (event, effect, timeout) otherwise it leads to errors.

In both of the examples below we use useEffect hook - to execute our code only once (at App component mount).

1. Insert property

To insert property to the object inside useState, we use:

  • spread operator (...) - to create new object, which is a copy of the existing user┬áand add new property to it,
  • setUser - to update our user with the new object.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const [user, setUser] = React.useState({ id: 1, name: 'Tom', age: 23 });

  React.useEffect(() => {
    setUser({ ...user, email: 'tom@email.com' });
  }, []);

  return <div>{JSON.stringify(user, null, 4)}</div>;
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

2. Remove property

To remove property from the object inside useState, we use:

  • spread operator (...) - to destructure our┬áuser┬áobject and create its copy -┬áchangedUser┬áwith all user properties except that specified with┬ápropertyKey. That approach removes our age property.
  • setUser - to update our user with the new object.
// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
   const [user, setUser] = React.useState({ id: 1, name: 'Tom', age: 23 });
   React.useEffect(() => {
       const propertyKey = 'age';
       const {[propertyKey]: propertyValue, ...changedUser} = user;
       setUser(changedUser);
   }, []);
   return <div>{JSON.stringify(user, null, 4)}</div>;
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Related posts

References

ReactJS

React - update object inside useState
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join