React 16.8, React useState Hooks are functions that add state variables to functional components and instrument the lifecycle methods of class components.
useState() is a Hook that allows you to maintain state variables in functional components. You can set the initial state to this function as optional and another function to update the state value.
What does the useState Hook do?
As stated previously, useState enables you to add state to function components. Calling React.useState inside a function component generates a single piece of state associated with that component.
Whereas the state in a class component is always an object, with Hooks, the state can be any type. Each state holds a single value, which can be an object, an array, a boolean, or any other type.
Declaring state in React useState is a named export from react. To use it, you can write:
React.useState
Or to import it just write useState:
import React, { useState } from 'react';The useState Hook allows you to declare only one state variable (of any type) at a time.You to declare more than one state variable in functional components.
import React, { useState } from 'react'; const Message= () => { const messageState = useState( '' ); const listState = useState( [] ); }useState takes the initial value of the state variable as an argument. This is similar to this.state and this.setState in a class component.
Update state with useState Hook:
function Usestatehook = () => { const [email, setEmail] = useState( '' ); return (Object state variable example:<input onchange="{e" type="text" value="{email}">setEmail(e.target.value)} /> Entered email : {email}); };
const [userObj, setUser] = useState({ id: 1, name: '', email: '' });
NOTE:
- Only call Hooks at the top level of functional components
- Don’t use useState in a class components
By watching below video, you can learn the concepts of react js useState hook with examples in Telugu.
0 Comments