Hey, Web Developers! In This Blog Post, We Will See All React Hooks And Explain Them With Clear Examples. React Hooks Are Functions That Let You Use State & Other React Features Without Writing Class.
Because Of This Feature Developers Can Build Web Applications That Are Cleaner & Manageable. We Will Walk Through Each Hook From The Basic Hooks Like ‘usesate’ And ‘useeffect’ To Advanced Hooks Like ‘usecontext & Usereducer.
So If You Are New To React Hook In React This Blog Post Will Help You Grasp The Concept Of Hooks And Guide You On How You Can Use Them To Create Advanced Frontend Web Applications.
Also Read: How To Set – Get Cookies With Express And MongoDB
React Hooks Are Special Functions In React That Allows You To Handle Sate & Manage Other React Features Without Writing Class. There are various types of hooks like useState, UseEffect, UseContext with specific functionality.
Now I Hope You Understand What The Hooks Are But How Many Types Of Hooks Are There In React? According To The React There Are 10 Types Of Hooks In React That Are Considered To Be The Part Of Core React Js & They Are As Follows:
So Now Let’s Get Into Each Hook Step By Step With Example:
useState
is used to manage the state within functional components in React.import React, { useState } from 'react'
const mystate = () => {
const [number, setNumber] = useState(0);
const Increment = ()=>{
setNumber(prenumber => prenumber+1);
}
const Decrement = ()=>{
setNumber(prenumber => prenumber-1);
}
return (
<>
<div>{number}</div>
<button onClick={Increment}>Increment</button>
<button onClick={Decrement}>Decrement</button>
</>
)
}
export default mystate
In This Example, We Have Created Two Buttons One For Incrementing The Value & Another For Decreasing The Value Respectively. Each button has an onClick event handler to perform its respective function.
We Use The useState
Hook To Create A State variable called number
with an initial value of 0. This state variable will hold our current number. The useState
hook also provides a function called setNumber
to update the value of number
.
When we click the increment button, it calls a function that increases the value of number
using setNumber
. Similarly, clicking the decrement button calls a function that decreases the value of number
.
The great thing about this approach is that we can create multiple state variables for different numbers and update their values using their respective set
functions, all declared in a similar manner.
useEffect
allows performing side effects in functional components.useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
Effect Definition: The useEffect hook takes a function as its first argument. This function contains the side effect we want to perform—in this case, updating the document’s title.
Dependency Array: The second argument to useEffect is an array of dependencies. The effect will only re-run if one of these dependencies changes. Here, the dependency is [count], which means the effect will re-run every time count changes.
Updating the Title: Inside the useEffect function, we set the document’s title to You clicked ${count} times. This ensures that whenever count changes, the document title is updated to reflect the new count.
useContext
provides a way to pass data through the component tree without having to pass props down manually at every level.const value = useContext(MyContext);
Importing useContext: First, make sure to import the useContext hook from React at the top of your file.
Creating Context: Assume we have a context called MyContext that we have created and provided a value for higher up in the component tree. This context might look something like this:
Accessing the Value: The useContext hook takes the context object as an argument and returns the current context value for that context. This allows any component in the tree to access the context value without having to pass props down manually.
useReducer
is an alternative to useState
for managing complex state logic in React.import React, { useReducer } from 'react';
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>You clicked {state.count} times</p>
<button onClick={() => dispatch({ type: 'increment' })}>
Increment
</button>
<button onClick={() => dispatch({ type: 'decrement' })}>
Decrement
</button>
</div>
);
}
export default Counter;
Initial State: We define an initial state object { count: 0 } that will hold our count value.
Reducer Function: The reducer function handles state changes based on the action type. It uses a switch statement to decide how to update the state.
useReducer Hook: We use useReducer to create state and dispatch. state holds the current state, and dispatch is a function we use to send actions to the reducer.
Rendering: We render a paragraph displaying the current count and two buttons: The increment button calls dispatch with an action of type ‘increment’ to increase the count.
The decrement button calls dispatch with an action of type ‘decrement’ to decrease the count.
useCallback
memoizes a callback function, preventing unnecessary re-renders in child components.const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
Using useCallback: Inside your component, we use the useCallback hook to create a memoized version of the callback function doSomething. This function will only be recreated if the dependencies [a, b] change.
Callback Function: We add the callback function as the first argument to useCallback. This is the function we want to memoize.
Dependency Array: The dependency array [a, b] tells React when to recreate the memoized function. If either a or b changes, useCallback will return a new version of the function. If neither changes, the same function instance is returned.
useMemo
memoizes a value computed from a function, preventing expensive computations on every render.const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
useRef
creates a mutable reference that persists across renders and doesn’t trigger re-renders when its value changes.const inputEl = useRef(null);
Using useMemo: Inside your component, we use the useMemo hook to memoize the result of a potentially expensive computation. The useMemo hook takes two arguments. A function that performs the computation and a dependency array.
Computation Function: The function passed to useMemo is responsible for computing the value.
Dependency Array: The dependency array [a, b] ensures that the memoized value is recalculated only when either a or b changes.
useImperativeHandle
customizes the instance value that’s exposed to parent components when using ref
.useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
Creating a Custom Component: We create a custom component that we want to expose imperative methods on. In this example, we are creating a component that wraps an input element and allows focusing on it imperatively.
Defining the Ref: We use forwardRef to forward a ref through our component to the input element inside it. This allows the parent component to directly interact with the input element.
Using useImperativeHandle: Inside the component, we use useImperativeHandle to define which methods should be exposed to the parent component. We pass the ref and a function that returns an object containing the methods we want to expose. In this case, we expose a focus method that calls the focus method on the input element.
useLayoutEffect
is similar to useEffect
, but it runs synchronously after all DOM mutations.useLayoutEffect(() => {
// DOM mutations
}, [dependencies]);
Using useLayoutEffect: Inside your component, we use the useLayoutEffect hook to perform side effects that involve DOM manipulations. The useLayoutEffect hook takes two arguments: a function and a dependency array.
Effect Function: The function passed to useLayoutEffect contains the code for the DOM manipulations. This code runs synchronously after all DOM mutations but before the browser repaints the screen.
Dependency Array: The dependency array [dependencies] ensures that the effect only runs when the specified dependencies change. This helps optimize the performance by running the effect only when necessary.
useDebugValue
adds a label to custom hooks for easier debugging in React DevTools.useDebugValue(isOnline ? 'Online' : 'Offline');
Using useDebugValue: Inside your custom hook or component, we use the useDebugValue hook to provide a readable label for our state. In this case, we are checking if the user is online or offline and labeling the state accordingly.
Conditional Label: The useDebugValue hook takes a value that will be displayed in React DevTools. Here, we use a ternary operator to check the isOnline state. If isOnline is true, the label will be ‘Online’. If isOnline is false, the label will be ‘Offline’.
Last Updated: August 10, 2024