Reputation: 1248
I was learning about React and comes across this "useState".
What is the pros and cons of using this in place of class with state?
Can it replace other lifecycle hooks? like componentDidMount
, componentDidUpdate
etc. ?
Upvotes: 1
Views: 3146
Reputation: 15393
The "useState" function in React is tied to its state system. The state system is kind of like a variable in the world of React. We make use of state to store data that gets changes over time as a user interacts with our data by clicking on things, typing on things and so on.
Anytime we update state, React will update the content that is on the screen. If you look at the example below:
export default function App() {
const [language, setLanguage] = useState("es");
const [text, setText] = useState("");
return (
<div>
<Field onChange={setText} />
<Languages language={language} onLanguageChange={setLanguage} />
<hr />
<Translate text={text} language={language} />
</div>
);
}
The above has three pieces of data that changes: 1. The text the user typed into the text input. 2. The language the user wanted to translate text to and 3. The result of the translation.
So we can find a single call to the useState()
function to set up each piece of the data.
So this one:
const [language, setLanguage] = useState("es");
says we are going to have some kind of selected language that will change over time.
This one:
const [text, setText] = useState("");
is tied to the text that the user adds in the input and then the third call is inside another component inside the Translate file that will have its own useState
call.
It can be a little bit confusing, but that's what practicing is all about.
Upvotes: 0
Reputation: 587
React useState is the React Hook that allows you to manage the state within functional components.
For example:
import React, { useState } from 'react'
const Example = () => {
// create the "counter" state
const [count, setCount] = useState(0)
return (
<div>
<p>Button clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Count + 1
</button>
</div>
)
}
export default Example
With useState you can easily create stateful functional components.
The old equivalent way, using class components with Component
class and setState
is:
import React, { Component } from 'react'
class Example extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
render() {
const { count } = this.state
return (
<div>
<p>Button clicked {count} times</p>
<button onClick={() => this.setState({ count: count + 1 })}>
Count + 1
</button>
</div>
)
}
}
export default Example
To replace lifecycle hooks like componentDidMount
or componentDidUpdate
you need to use the useEffect
hook for functional components.
Source:
Links:
Upvotes: 0
Reputation: 1
It is a concept of React Hook. With the help of useState
we can define and update the state in the functional component too. It is considered as a main advantage of React Hooks.
Here is an example:
//using class component
import React from 'react'
//using Class component
export default class App extends React.Component {
constructor() {
super()
this.state = {
count: 0
}
this.increment = this.increment.bind(this);
}
increment = () => {
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<div>
<button onClick={this.increment}>click</button>
<h1>count:{this.state.count}</h1>
<Counter />
</div>
)
}
}
//using reacthook
export default function Counter() {
const [count, setState] = useState(0);
return (
<div>
<button onClick={() => setState(count + 1)}>Click</button>
<h1>count:{count}</h1>
</div>
);
}
From the example, we can find that React Hooks simplify the code by using state and setting state in the functional component and also overcome the problem of using this keyword complexity.
Upvotes: 0
Reputation: 49182
import React, {useState} from "react";
const [count,setCount]=useState(0)
This is an array destructuring. useState(0) returns an array with two elements inside of it. First element is referred to as the current value. Second element of that array is a setter function. It is a function that allows us to update the value of this piece of state. It is equivalent to calling setState() inside of a class based component. On the right side, we have useState function and then inside there we provide an initial value for this piece of state. Inside of our class based component our state was an object that had a bunch of different values inside of it. When we make use of the useState() hook, we instead usually just store the single value that we care about. We kind of move away from an object containing all of our state to just the individual values themselves. The reason for this is that we can call useState() as many as we wish.
In general React wants you to call the state multiple times for the multiple things you are tracking. But your state can be object too.
const [state, setState] = useState({
count: props.count,
text: "" });
you have to be careful here. Because, with useState() whenever we try to change the state by calling setState function, it is not merging those objects. Instead it is completely replacing the old state with the new state.
imagine you have a button with this onClick method
const decrement = () => {
setState({ count: state.count - 1 }); };
when you click on the button, "count" property will change but "text" property will disappear. we work around this with spread operator.
const decrement = () => {
setState({...state, count: state.count - 1 })
};
We spread state object first. since "count" property is already a part of the state object, setstate() will just change the "count" property inside the state object.
Upvotes: 0
Reputation: 4182
UseState was released as part of react-hooks. Basically with the introduction of hooks you are no longer being forced to use classes just to be able to make use of react core features such as the state. You can now manipulate the state by using a function-based component.
On clicking the state will be modified to Jimmy.
And yes, you can access prevState and make API calls too.
const User = () => {
const [userInfo, setUserInfo] = React.useState({
firstName: 'John', lastName: 'Doe',
});
return (
<div>
<p>userInfo: {JSON.stringify(userInfo)}</p>
<button onClick={() => setUserInfo({ firstName: 'Jimmy' })}>Update name to Jimmy</button>
</div>
);
}
Upvotes: 5