Introduction of hooks?
it allow you to use state and other react features without written a class.
Hooks allow function components to have acess to state and other react features like life cycle methods.
Because of this, class components are generally no longer needed.
Hooks wew added to react in 16.8(February 16, 2019).
What is Hooks?
Hooks are basically functions.
Hooks allow us to "Hook" into react features such as state and lifecycle methods.
HOOKS RULES:-
Hooks can only be called inside react function component.
Hooks can only be called at top level of a component.
We should not call hooks inside loops, conditions or nested function.
Only call hooks from react function, we sholud not call hooks from regular javascript function.
hooks cannot be conditional.
React relies on the order in which hooks are called.
Hooks are not used for class based component.
CUSTOM HOOKS:-
If you have stateful logic that needs to be reused in several components, you can build your own custom hooks.
When to use a hooks
if you write function component, and then you want to add some state to it,previously yod do this by converting it to a class.
But, now you can do it by using a hook inside the existing function component.
Hooks available
There a lots of built in hooks are available.
useState
useEffect
useContext
useRef
useReducer
usseCallback
useMemo
Custom Hooks
useState hook
Hook state is the new way of declaring a state in react app.
Hook uses useState() functional component for setting and retriving state.
The react useState Hook allows us to track state in a function component.
State generally refers to data or properties that need to be tracing in an application.
Import useState:-
To us ethe useState Hooks, we first need to import it into our component.
At the top of your component, import the useState Hooks.
import { useState } from "react";
Notice that we are destruction useState from react as it is a named export.
Intialize useState:-
We intialize our state by calling useState in our function component.
useState accepts an intial state and return two value:
The current state.
A function that updates the state.
Intialize state at the top of the function component.
Notice that again, we are destructuring the return valures from useState.
import { useState } from 'react'
function User() {
const [name,setname] = useState("riya")
let changename = () => {
setname("siya")
}
return (
<div>
<h1>{name}</h1>
<button onClick={changename}>click</button>
</div>
)
}
Update state:-
To update our state, we use our state updater function.
We should never directly update state, Ex: color="red" is not allowed.
What can state hold:-
The useState Hooks can be used to track of string, number, boolean,array,object and any combination of these
We could create multiple state hooks to track individual values.
function car(){
const [brand,setBrand] = useState("Ford");
const [model,setModel] = useState("Mustang");
const [color,setcolor] = useState("white");
}
Object in useState:-
function User() {
const obj = {
name:"Megha",
age:23,
isYoung:true
}
const [person,setPerson] =useState(obj);
const changeState = () => {
setPerson({
name:"Megha Khatri",
age:12,
isYoung:false
})
}
return (
<div>
<h1>{person.name}</h1>
<h1>{person.age}</h1>
<h1>{person.isYoung.toString()}</h1>
<button onClick={changeState}>change state</button>
</div>
)
}
Update only one state:-
When state is updated, the entire state gets overwritten.
when if we only want to update the name of a person?
if we only called setPerson({name:"Megha Khatri"}), this would remove the age,height and isYoung from our State.
We can use the JS spread operator(...) to help us.
function User() {
const obj = {
name:"Megha",
age:23,
isYoung:true
}
const [person,setPerson] =useState(obj);
const changeState = () => {
setPerson(previousState => {
return {
...previousState,
name:"Megha Khatri"
}
});
return (
<div>
<h1>{person.name}</h1>
<h1>{person.age}</h1>
<h1>{person.isYoung.toString()}</h1>
<button onClick={changeState}>change state</button>
</div>
)
}
Spread Operator:-
The JS spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object
Updating object in state:-
Because we need the current value of state, we pass a function into our setPerson function. This function receives the previous value.
We then return an object, spreading the previousState and overwritten only the name.
useState with Array:-
function User() {
let num=[1,2,3,4,5,6];
let [number,setNumber]= useState(num);
const changeList= () =>{
setNumber([11,22,33,44,55,66]);
}
return (
<div>
<ul>
{number.map((n, i) => <li key={i}>{n}</li>)}
</ul>
<button onClick={changeList}>Change</button>
</div>
)
}
Add a Randdom number in array:-
function User() {
let num=[1,2,3,4,5,6];
let [number,setNumber]= useState(num);
const changeList= () =>{
setNumber(priviousState =>{
return [
...priviousState,
Math.floor(Math.random()*50)
]
});
}
return (
<div>
<ul>
{number.map((n, i) => <li key={i}>{n}</li>)}
</ul>
<button onClick={changeList}>Change</button>
</div>
)
}
HAPPY LEARNING...