0% found this document useful (0 votes)
77 views

useState( ) Hook in ReactJs PDF

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

useState( ) Hook in ReactJs PDF

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

useState( ) Hook in ReactJs

Notes By Priyanka Bhargava

Lecture By Huxn WebDev

Channel Link https://www.youtube.com/@huxnwebdev

State and Hooks


1. State
a. State is a way to store and manage data that can change over time and affects how
the component renders.

b. We define state using the useState Hook

Which allows you to set an initial value and provides a way to update that state.

2. Hooks

a. Hooks are a new addition in React 16.8.


b. They let you use state inside the function component and other React features
without writing a class-based component.

c. Back in time, we were using class-based components like everywhere.

d. But now a days,we only use function-based components.

e. Nobody uses a class-based component.

f. There are a lot of Hooks.

useState( ) Hook
1. useState( )

a. useState Hook allows us to track state in a functional component.

b. State generally refers to data or properties that need to be tracked in an application.

2. Syntax

useState( ) Hook in ReactJs 1


const[data, changeData] = useState( )

Write useState( ) Hook

Then use Array Destructuring

data : initial value

changeData : Change value

3. useState( ) returns

a. Initial value for state.

b. Function which will allow us to change value.

import { useState } from "react";

const App = ()=>{


const counter = useState('Priyanka')
console.log(counter)
}

export default App

4. Convention to use useState( )


a. Destructure it by using Array destructuring.

Destructure initial value and function

useState( ) Hook in ReactJs 2


import { useState } from "react";

const App = ()=>{


const [count, setCount] = useState(0)
const increment =()=> setCount(count+1)
const decrement =()=> setCount(count-1)
return <section>
<h1>{count}</h1>
<button onClick={increment}>+</button>
<br />
<br />
<button onClick={decrement}>-</button>
</section>
}

export default App

Direct Implementation of set method in button onClick event.

const App = ()=>{


const [counter,setCounter] = useState(0)
console.log(counter)

useState( ) Hook in ReactJs 3


return <div>
<h1>counter : {counter}</h1>
<button onClick={()=>setCounter(counter+
1)}>Increment</button>
<br />
<br />
<button onClick={()=>setCounter(counter-
1)}>Decrement</button>
</div>
}

export default App

5. Can we change value of count without changing value of setCount?

a. Behind the scenes the counter is updating but UI is not updating.

b. setCount method allows us to change value of our state, our component will
rerender.

c. Anytime we change the value of our state by using setCount method or any set
method, it’s going to rerender our application.

d. It will change the value of state but it will not rerender our application.

useState( ) Hook in ReactJs 4


Array useState
1. Render Over Array useState

const App = ()=>{


const [friends,setFriends] = useState(["Priyanka","S
anaya","Yash","Laxmi","Rahul"])

return <div>
<h1>Friends</h1>
<ol>
{friends.map((friend,index)=>(
<li key={index}>{friend}</li>
))}
</ol>

</div>
}

export default App

useState( ) Hook in ReactJs 5


2. import React from 'react'
import {useState} from 'react'

const App = ()=>{


const [friends,setFriends] = useState(["Priyanka","S
anaya","Yash","Laxmi","Rahul"])

return <div>
<h1>Friends</h1>
<ol>
{friends.map((friend,index)=>(
<li key={index}>{friend}</li>
))}
</ol>
<button onClick={()=>setFriends([...friends,["Pr
anshu"]])}>Add Friend</button>
<button onClick={()=>setFriends(friends.filter(f
riend=>friend!=='Rahul'))}>Remove Friend</button>
<button onClick={()=>setFriends(friends.map(f=>f
==='Sanaya'?'Sanaya Trivedi' : f))}>Update Friend</butto
n>

useState( ) Hook in ReactJs 6


</div>
}

export default App

Object useState
import React from 'react'
import {useState} from 'react'

const App = ()=>{


const [movies,setMovies] = useState(
{
title : "Krish",
ratings : 7
}
)

return <div>

useState( ) Hook in ReactJs 7


<h1>Title : {movies.title}</h1>
<h1>Ratings : {movies.ratings}</h1 >
<button onClick={()=>setMovies({ ...movies,ratings:
5})}>Change Rating</button>

</div>
}

export default App

1. Initial State

2. After Clicking Event State

useState( ) Hook in ReactJs 8


Array of Objects State
import React from 'react'
import {useState} from 'react'

const App = ()=>{

const [movies,setMovies] = useState(

[
{id:1,title:"Avatar",ratings:6},
{id:2,title:"Superman",ratings:7},
{id:3,title:"Twilight",ratings:9}
]
)

return <div>
<ol>
{

useState( ) Hook in ReactJs 9


movies.map(
movie => (
<li key={movie.id}>Title : {movie.titl
e}</li>
)
)
}
</ol>

<button onClick={()=>setMovies(
movies.map(movie => movie.id=== 1 ?{...movie,ti
tle:"Jumanji"} : movie))}>Change Name</button>

</div>
}

export default App

1. Initial State

2. State after clicking button

useState( ) Hook in ReactJs 10


Defining State in Parent Component and
Sharing State in Children Components
1. Define state in App Component

2. Share state with Componentone and Componenttwo

a. By using props

3. From child component we update parent component.

a. State is available inside parent component

4. Child Component

a. Componentone

const Componentone = ({count,onClick})=>{


return <div>
<h1>Child Component 1 : {count}</h1>
<button onClick={onClick}>Increment</button>
</div>

export default Componentone

b. Componenttwo

useState( ) Hook in ReactJs 11


const Componenttwo = ({count,onClick})=>{
return <div>
<h1>Child Component 2 : {count}</h1>
<button onClick={onClick}>Decrement</button>
</div>

export default Componenttwo

5. Parent Component

import {useState} from 'react'


import Componentone from './components/Componentone'
import Componenttwo from './components/Componenttwo'

const App = ()=>{


const [count,setCount] = useState(0)

return <div>
<h1>Parent Component : {count}</h1>
<button onClick={()=>setCount(count+1)}>Incremen
t</button>
<Componentone count={count} onClick={()=>setCoun
t(count+1)}/>
<Componenttwo count={count} onClick={()=>setCoun
t(count-1)}/>

</div>

useState( ) Hook in ReactJs 12


}

export default App

6. Output of State Change

a. Initial Output

b. Triggering Count through Parent Component

useState( ) Hook in ReactJs 13


c. Triggering Count through Child Component 1

d. Triggering Count through Child Component 2

useState( ) Hook in ReactJs 14


Passing Function as Initial Value for useState
1. ExampleOne

import {useState} from "react"


const ExampleOne = ()=>{
const [count,setCount] = useState((value=0)=>{
return value
})
return <div>
<h1>count : {count}</h1>
<button onClick={()=>setCount((value)=>value+1)}
>Increment</button>
<br />
<br />
<button onClick={()=>setCount(value=>value-1)}>D
ecrement</button>
</div>

useState( ) Hook in ReactJs 15


export default ExampleOne

2. ExampleTwo

import { useState } from "react"


const ExampleTwo = ()=>{
const [randomNum , setRandomNum] = useState(
()=>Math.floor(Math.random()*100)
)
return <div>
<h1>Random Number : {randomNum}</h1>
<button onClick={()=>setRandomNum(()=>Math.floor
(Math.random()*100))}>Generate Random Number</button>
</div>
}

export default ExampleTwo

3. ExampleThree

Challenge
Exercise: Mastering useState in React
In this exercise, you’ll learn how to use the useState hook for managing state in various
scenarios, including basic usage, arrays, objects, and arrays of objects.

Step 1: Basic Usage of useState

useState( ) Hook in ReactJs 16


1. Create a new file called Counter.jsx .

2. Inside this file, create a functional component called Counter .

3. Use useState to manage a simple counter state.

Initialize the state with a value of 0 .

Create a button to increment the counter by 1 when clicked.

Display the current value of the counter.

import { useState } from "react"


const Counter = ()=>{
const [counter,setCounter] = useState(0)
return <div style={{display:"flex",flexDirection:"co
lumn",justifyContent:"center",alignItems:"center"}}>
<h1>Counter Calculator</h1>
<h1>{counter}</h1>
<button onClick={()=>setCounter(counter+1)}>Incr
ement</button>
<br />
<button onClick={()=>setCounter(counter-1)}>Decr
ement</button>

</div>
}

export default Counter

useState( ) Hook in ReactJs 17


Step 2: useState with an Array of Data

1. Create a new file called TodoList.jsx .

2. Inside this file, create a functional component called TodoList .


3. Use useState to manage an array of todo items.

Initialize the state with an empty array.

Create a form to add new todo items to the list.

Display the list of todo items.

import { useState } from "react";

const TodoList = ()=>{


const [tasks,setTasks] = useState([])
const [inputValue,setInputValue] = useState("")

// Tasks ko handle kiya jayega onSubmit event pe jab


bhi hum kisi task ko submit karke add karenge
const handleSubmit = (e)=>{
e.preventDefault() //Isse task submit karne ke b
aad TodoList appear hone ke baad gayab nahi hogi
setTasks([...tasks,inputValue]) //Isse tasks arr
ay me inputValue as task add hojayegi aur vo change huma
ri array pe jab hum map() function ke through jab iterat
e karenge tab humare Todo List me nazar aayega.
setInputValue("") //Isse har bar task submit kar
ke add karne ke bad inputValue dubara empty hojayegi

useState( ) Hook in ReactJs 18


}

// Input Values ko handle kiya onChange event pe jab


hum input field pe koi bhi task ko as string type kareng
e
const handleChange = (e)=>{
setInputValue(e.target.value)

return <div style={{display:"flex",flexDirection:"co


lumn",justifyContent:"center",alignItems:"center"}}>
<h1>Todo List</h1>
<form onSubmit={handleSubmit}>
<input type="text" value={inputValue} placeh
older="Enter Your Task" onChange={handleChange}/>
<button type="submit">Add Task</button>

</form>

<ol>
{
tasks.map((task,index)=>(
<li key={index}>{task}</li>
))
}
</ol>
</div>

export default TodoList

useState( ) Hook in ReactJs 19


Step 3: useState with an Object of Data

1. Create a new file called Profile.jsx .

2. Inside this file, create a functional component called Profile .


3. Use useState to manage an object with user profile information.

Initialize the state with an object containing name and age .

Provide input fields to update the name and age .

Display the updated profile information.

import { useState } from "react"


const Profile = ()=>{
const [profile,setProfile] = useState({
name : "Priyanka",
age : 27
})
const update = ()=>setProfile({...profile,name:"Priy
a",age:28})

return <div style={{display:"flex",flexDirection:"co


lumn",justifyContent:"center",alignItems:"center"}}>
<h1>Person Profile</h1>
<h2>Name : {profile.name}</h2>
<h2>Age : {profile.age}</h2>
<button onClick={update}>Update Profile</button>

</div>
}

useState( ) Hook in ReactJs 20


export default Profile

Step 4: useState with an Array of Objects

1. Create a new file called ShoppingList.jsx .

2. Inside this file, create a functional component called ShoppingList .


3. Use useState to manage an array of objects, where each object represents a shopping
item with name and quantity .

Initialize the state with an empty array.


Create a form to add new items to the list.

Display the list of shopping items.

import { useState } from "react"

const ShoppingList = ()=>{


const [products,setProducts] = useState([
])
const [inputName,setInputName] = useState("")
const [inputQuantity,setInputQuantity] = useState
("")

const handleSubmit = (e)=>{


e.preventDefault()
if(inputName.trim() && inputQuantity.trim()){
setProducts([...products,{name : inputName,q
uantity : inputQuantity}])
setInputName("")
setInputQuantity("")
}
}
const handleNameChange = (e)=>{
setInputName(e.target.value)
}

useState( ) Hook in ReactJs 21


const handleQuantityChange = (e)=>{
setInputQuantity(e.target.value)
}

return <div style={{display:"flex",flexDirection:"co


lumn",justifyContent:"center",alignItems:"center"}}>
<h1>Add Products in Shopping List Table</h1>

<form onSubmit={handleSubmit}>
<input type="text" value={inputName} placeho
lder="Enter Product Name" onChange={handleNameChange}/>
<input type="text" value={inputQuantity} pla
ceholder="Enter Quantity" onChange={handleQuantityChang
e}/>
<button>Add Product</button>
</form>
<br />

{/* Iterate Over Shopping List */}


<table align="center" border="1" style={{borderC
ollapse : " collapse",width : "50%"}}>
<thead>
<tr>
<th>S.No.</th>
<th>Product Name</th>
<th>Product Quantity</th>
</tr>
</thead>
<tbody align="center">
{
products.map((product,index)=>(
<tr key={index}>
<td >{index+1}</td>
<td >{product.name}</td>
<td >{product.quantity}</td>

useState( ) Hook in ReactJs 22


</tr>
))
}
</tbody>
</table>
</div>
}

export default ShoppingList

Step 5: Render All Components in App.jsx

1. In your App.jsx file, import the Counter , TodoList , Profile ,


and ShoppingList components:

import Counter from "./Counter";


import TodoList from "./TodoList";
import Profile from "./Profile";
import ShoppingList from "./ShoppingList";

2. Inside the App component, render all four components:

import React from 'react'


import Counter from './components/Counter'
import TodoList from './components/TodoList'
import Profile from './components/Profile'
import ShoppingList from './components/ShoppingList'

const App = ()=>{

return <div>
<Counter/>
<hr style={{border : "none",height :"10px", back
groundColor:"black"}}/>
<TodoList/>

useState( ) Hook in ReactJs 23


<hr style={{border : "none",height :"10px", back
groundColor:"black"}}/>
<Profile/>
<hr style={{border : "none",height :"10px", back
groundColor:"black"}}/>
<ShoppingList/>

</div>
}

export default App

Initial State of all Components

useState( ) Hook in ReactJs 24


After Changing State of All Components

useState( ) Hook in ReactJs 25


useState( ) Hook in ReactJs 26

You might also like