useState( ) Hook in ReactJs PDF
useState( ) Hook in ReactJs PDF
Which allows you to set an initial value and provides a way to update that state.
2. Hooks
useState( ) Hook
1. useState( )
2. Syntax
3. useState( ) returns
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.
return <div>
<h1>Friends</h1>
<ol>
{friends.map((friend,index)=>(
<li key={index}>{friend}</li>
))}
</ol>
</div>
}
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>
Object useState
import React from 'react'
import {useState} from 'react'
return <div>
</div>
}
1. Initial State
[
{id:1,title:"Avatar",ratings:6},
{id:2,title:"Superman",ratings:7},
{id:3,title:"Twilight",ratings:9}
]
)
return <div>
<ol>
{
<button onClick={()=>setMovies(
movies.map(movie => movie.id=== 1 ?{...movie,ti
tle:"Jumanji"} : movie))}>Change Name</button>
</div>
}
1. Initial State
a. By using props
4. Child Component
a. Componentone
b. Componenttwo
5. Parent Component
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>
a. Initial Output
2. 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.
</div>
}
</form>
<ol>
{
tasks.map((task,index)=>(
<li key={index}>{task}</li>
))
}
</ol>
</div>
</div>
}
<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 />
return <div>
<Counter/>
<hr style={{border : "none",height :"10px", back
groundColor:"black"}}/>
<TodoList/>
</div>
}