Antony
Antony

Reputation: 323

React: How to use setState inside functional component?

I am learning React. I read an article that suggests us to use functional component instead of class that extends React.Component, so I followed. I also use the arrow function instead of function keyword. That is:

const MyComponent = (props) => {...}

I got a structure that has 20 properties like:

{
    id: '',
    firstname: '',
    lastname: '', 
    ...
}

I am using if ... else if ... to set the state, but I saw some examples that use this.setState() in just one line of code. I try to import setState from 'react', but fail.

Is there a way to use setState() instead of setName(), setId(), ..., etc? Or any suggestion?

Thank you very much!

Upvotes: 16

Views: 61449

Answers (4)

Mayank Singh
Mayank Singh

Reputation: 43

Class-based components and functional components both have different ways of storing and setting values in them.

In class-based components, this.state is used which is usually of an object nature and holds all the values needed in the components, here setState() function is used to do a shallow update to this.state object. (It will merge the prev and new object)

In function-based components state can be stored using useState hook. The name of the state variable can be anything. Just like the class component here, we have two items returned by the useState hook. The first item represents the variable and the second represents the setter function.

Now,

To useState variable is declared like,

const [banana, setBanana] = useState("initial value - could be string, number, object");

To use the variable in the component just use the variable name "banana" and set a new value in the variable using the setter function like,

setBanana("good banana");

This will change the initial value to whatever you set it to. If the variable was an object, it will be replaced by the new object not shallow merged.

Also, inside a function-based component, you can have any number of useState variables. The important thing to keep in mind is if multiple of them are called in a function call batching is performed.

Refs:-

  1. https://react.dev/reference/react/Component#setstate
  2. https://legacy.reactjs.org/docs/hooks-state.html#declaring-a-state-variable

Upvotes: 0

Faizan Ahmed
Faizan Ahmed

Reputation: 214

this.setState only works in class based components. In functional components useState hook is used which behaves as a state

useState lets you add React state to function components.

Upvotes: 4

DennisVM-D2i
DennisVM-D2i

Reputation: 488

There is only the (one) 'setState()' method - not a method per-property (as you've suggested/questioned).

It is a composite in terms of it's parameter, in that you can specify/set more than one item within the same/one call (to the 'setState()' method), so you can set all 20 of your items in one go.

E.g.

  this.setState({ "firstName" : firstNameVal, "lastName" : lastNameVal });

I was starting from where you said you started - from a 'class' based component.

If you are sticking with the switch to a 'function' based component, then it is slightly different, in summary:

import React, { useState } from 'react';

...

// The 'useState' hook (function) returns a getter (variable) & setter (function) for your state value - and takes the initial/default value for it/to set it to, e.g.
const [ firstName, setFirstName ] = useState('');

And you then use the getter var to read it & the setter function to set it:

  setFirstName('Dennis');

(I could be wrong but I believe 'hooks' were added in v16.8 of React.)

A more in-depth description:

https://www.simplilearn.com/tutorials/reactjs-tutorial/reactjs-state#:~:text=1%20A%20state%20can%20be%20modified%20based%20on,merge%20between%20the%20new%20and%20the%20previous%20state

Upvotes: 9

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11011

Use useState hook in functional components.

const App = () => {
  const [state, setState] = React.useState({ first: "hello", second: "world" });
  
  return (
    <div>
      <input type="text" value={state.first} onChange={(ev) => setState({...state, first: ev.target.value})} />
      <input type="text" value={state.second} onChange={(ev) => setState({...state, second: ev.target.value})} />
    </div>
  )


}


ReactDOM.render(<App />, document.getElementById('app'))
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id="app"> </div>

Upvotes: 8

Related Questions