In this article we are going to talk about useState
hooks in React and how to use it.
useState Hooks ? What is it ? π³
useState
is a React hooks that allow us to use and to modify the state in our function component(before called stateless component) without to write a class component and setState
method.
In the previous version of React before the react@16.8
, the using of state and update the state in our component was like this :
import React from 'react'
class App extends React.Component() {
constructor(props) {
super(props)
this.state = {
name:"Emmanuel",
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(e){
this.setState({name:e.target.value})
}
render(){
return(
<div>
<p>{this.state.name}</p>
<input value={this.state.name} type="text" name="name" handleChange={this.handleChange}/>
</div>
)
}
}
Since the hooks are been introduced in React, the way to use the state and to modify the state are become easy. We are going to modify the previous code and to write a functional component with useState hooks.
import React, { useState } from 'react';
function App(props){
const [name, setName] = useState('Emmanuel')
function handleChange(e){
setName(e.target.value)
}
return(
<div>
<p>{name}</p>
<input value={name} type="text" name="name" onChange={handleChange}/>
</div>
)
}
Like we see in the fist line of our code, we have imported the useState
hooks. the setName
function passed to onClick event allow to update our name
state.
How useState
hooks works
const [state, setState] = useState(initialState);
It returns a stateful value, and a function to update it.During the initial render, the returned state is the same as the value passed as the first argument (initialState). The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component. During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates. React guarantees that setState function identity is stable and wonβt change on re-renders.
The state value can be a object, array, number, string, boolean, etc...
Note β
If you want to use the useState
hooks in your code and if you have already write your code with the Class
method, please don't delete your code, you can update the version of your React application (react
and react-dom
) to the new version supported the hooks and continue to build your application using the useState
in the new component created.
Top comments (1)
Hi Emmanuel,
thank u for this valuable article it is really helpful,
i have a point wanna ask about
i have tried using hooks in an app that i am working on
but there is something i do not understand there is stale state in my functions,
how can i override this, how can i get the latest values of a specific state variable inside one of my functions?!
thank u