Introduction
Hooks in React allows you to hook into the react state and lifestyle features through the function component. Hooks are a new feature update of the React in version 16.81. Hooks allow us to use the functionality of various states and React features without using the class. The useEffect() considers a function observing input and returns nothing; it runs additional code after render. We can see it as a combination of React Component lifecycle methods: componentDidMount, componentDidUpdate, and componentWillUnmount. Using Effect Hooks, we can add listeners after the component has been rendered. The Effect Hook allows us to perform side effects in function components. Functions like data fetching, setting up a subscription, and manually changing the DOM in React components are part of these side effects. They can also be just called effects.
There are two different types of side effects which the React Hook provides us:
- Effects without a CleanUp
- Effects with a CleanUp
Effects without Cleanup
Effect Hooks without cleanup are used in useEffect, so it does not block the browser from updating the screen. This makes our app more responsive. The most common effects that don't require a cleanup are manual DOM mutations, Network requests, Logging, etc.
All the examples we have discussed till now are effects that do not require cleanup.
For example,
import React, { useState, useEffect } from "react"; function CountNinja() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>Ninja clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); } |
OUTPUT