An Interest In:
Web News this Week
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
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
- useState
- useEffect
Why do we prefer functional component over class component in react
- Functional component is much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks
- Functional component are written shorter and more straightforward, which makes it easier to develop, understand, and test.
- With the introduction of Hooks in we are now able to manage state in functional components.
What is Hooks?
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.
What is useState Hook?
useState is a Hook which allows you to have state variables in functional components.
- First of all, let us import
useState
hook from react.
import React, { useState } from "react";
- How to use:
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.
Example
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;
Code Sandbox Sample
Here is the example of the above blog. Feel free to play with it.
Conclusion
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
- useState
- useEffect
If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter here.
Original Link: https://dev.to/pratap2210/usestate-react-hooks-series-pm9
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To