33
useState - React Hooks Series
Welcome to the hooks series of react. In this series, I will go through the different hooks which were introduced in React 16.8.
Series path
Hooks were a new addition in
React 16.8
. They let you use state and other React features without writing a class. It means you don't need to use a class component to use a state.useState is a Hook which allows you to have state variables in functional components.
useState
hook from react.
import React, { useState } from "react";
const [name, setName] = useState("Pratap");
Let us try to understand what we just added:
name
: State Variable.setName
: Function to change the state value.useState
: useState react Hook.Pratap
: State initial value.import React, { useState } from "react";
const Example = () => {
const [name, setName] = useState("Pratap");
return (
<div>
<h1>{name}</h1>
</div>
);
};
export default Example;
Now, let us add a button which will change the state value from
Pratap
to Prasar
.import React, { useState } from "react";
const Example = () => {
const [name, setName] = useState("Pratap");
const changeState = () => {
//This will change the state value
setName("Prasar");
};
return (
<div>
<h1>{name}</h1>
<button onClick={changeState}>Change Name</button>
</div>
);
};
export default Example;
In the next article in this React Hooks series, we will get to know and see about useEffect hooks.
Thank you for reading my first part in the React Hooks Series!
Series path
💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter here.
33