React Hooks
What is hook?
Hooks allows function components to have access to state and other React features.
Types of hooks
We have several types of react hooks which is used to manage React State.
useState, useEffect, useLayoutEffect, useContext, useRef, useReducer, useCallback, useMemo
Also we can create CustomHooks
useState:
useState hook allows us to track state in Function Component.
Which refers data or properties that need to be tracking in an application.
import React, { useState } from "react";
In the below example used count and color variables for changing the value when buttons are clicked.
import React, { useState } from "react";
const Display = () => {
// The React useState Hook allows us to track state in a function component.
const [count, setCount] = useState(0); // Initially setting count to 0
const [color, SetColor] = useState("black"); // Initially setting black color
const btnSetColor = () => {
SetColor("orange");
};
return (
<div style={{ margin: "20px" }}>
<label>{count}</label>
<br />
<br />
<button
onClick={() => {
setCount(count + 1);
}}
>
Click
</button>
<br />
<br />
<button onClick={btnSetColor}>Set Color</button>
<br />
<br />
<div
style={{ height: "100px", width: "100px", backgroundColor: color }}
></div>
</div>
);
};
export default Display;
Output: Before click
Output: After click
useEffect:
The useEffect Hook allows you to perform side effects in your components.
Some examples of side effects are: fetching data, directly updating the DOM, and timers.
useEffect accepts two arguments. The second argument is optional.
useEffect(<function>, <dependency>)
Example:
import React, { useEffect, useState } from "react";
const Display = () => {
// The React useState Hook allows us to track state in a function component.
var [count, setCount] = useState(0); // Initially setting count to 0
const [calculation, setCalculation] = useState(0); // Initially setting calculation to 0
// On button click setCount method will trigger and it will increase the count by 1
// useEffect(<function>, <dependency>)
// use effect will execute when count increases
// count is depedency for this effect now once count increases useEffect will trigger
useEffect(() => {
// multiplying current value with 2
setCalculation(() => count * 2);
}, [count]); //
return (
<div style={{margin:'20px',backgroundColor:'cyan', padding:'20px'}}>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</div>
);
};
export default Display;
useContext:
useContext is used to manage the state globally.
Provider is used to send the data, Consumer is used to receive the data.
App.js
import React from "react";
import ComponentC from "./ComponentC";
// useContext creating context
export const UserContext = React.createContext();
const App = () => {
// Provider is used to send the data to particular component
return (
<div>
<UserContext.Provider value={"Testing useContext"}>
<ComponentC />
</UserContext.Provider>
</div>
);
};
export default App;
ComponentC.js
import React, { useState } from "react";
import { UserContext } from "./App";
const ComponentC = () => {
const [value, SetValue] = useState("");
// Consumer is used to recieve the data from base component
return (
<div>
<center>
<UserContext.Consumer>
{(val) => <div>{SetValue(val)}</div>}
</UserContext.Consumer>
Component C {value}
</center>
</div>
);
};
export default ComponentC;
Output
useRef:
useRef Hook allows you to persist values between renders.
It can be used to access a DOM element directly.
App.js
import React, { useEffect, useRef, useState } from "react";
const App = () => {
const data = useRef("");
const submitHandler = (e) => {
e.preventDefault();
console.log(data.current.value);
};
useEffect(() => {
data.current.focus();
}, []);
return (
<div>
<form onSubmit={submitHandler}>
<center>
<input type="text" ref={data} placeholder="Enter User Name" />
<br />
<input type="submit" />
</center>
</form>
</div>
);
};
export default App;
useReducer:
The reducer function contains your custom state logic and the initialstate can be a simple value but generally will contain an object.
The useReducer Hook returns the current state and a dispatchmethod.
App.js
import React, { useReducer } from "react";
import { reducer } from "./reducer";
const initialState = { count: 0 };
const App = () => {
const [state, dispath] = useReducer(reducer, initialState);
return (
<div>
<center>
Count: {state.count}
<button onClick={() => dispath({ type: "INCREMENT" })}>+</button>
<button onClick={() => dispath({ type: "DECREMENT" })}>-</button>
</center>
</div>
);
};
export default App;
reducer.js
export function reducer(state,action){
switch (action.type) {
case "INCREMENT":
return {count: state.count + 1};
case "DECREMENT":
return {count: state.count - 1};
default:
return new Error();
}
}
Output:
useMemo:
useMemo hook is used to avoid calling a function un-necessarily, It will improve the performance of application.
Preventing methods to stop calling un-necessarily.
Code Example:
import React, { useMemo, useState } from "react";
const App = () => {
const [counter, setCounter] = useState(0);
const [number, setNumber] = useState(5);
// fact function will call when ever the dependency is changed when we use useMemo
const Factorial = useMemo(() => fact(number), [number]);
return (
<div>
<center>
Factorial Value of {number} is {Factorial}
<br />
<button onClick={() => setCounter(counter + 1)}>
Counter Increment
</button>
<br />
<button onClick={() => setNumber(number + 5)}>
Fact Number Incrment
</button>
<br />
counter : {counter}
</center>
</div>
);
};
const fact = (n) => {
let answer = 1;
for (var i = n; i >= 1; i--) {
answer = answer + i;
}
console.log("Factorial function calling!");
return answer;
};
export default App;
Use Memo Output Videos: