Yogesh Chauhan's Blog

Effects in React

in React on July 6, 2021

React introduced hooks in versino 16.8.

What does a hook do?

Basically a hook let you use state and some other features in React, without writing a class. Basically you perform some sort of side actions/effects in the function components itself.

We can make this equation from React class lifecycle methods.

useEffect = componentDidMount + componentDidUpdate + componentWillUnmount

There are two different kinds of side effects. One of those type requires a cleanup afterwards and the other one doesn’t.

Effects Without Cleanup

Performing activities like logging of some variable doesn’t require a clean up. That means you run some code and that’s it. It’s not going to change anything else in the app. So, you can run it and then forget about it.

In this post, How states work in React?, I have a lifecycle methods example.

So, basically what you can do using these two methods in a class

componentDidMount() {
  document.title = `You clicked ${this.state.count} times`;
componentDidUpdate() {
  document.title = `You clicked ${this.state.count} times`;

… can be done by using the hook in a function component:

import React, { useState, useEffect } from 'react';
const [count, setCount] = useState(0);

useEffect(() => {
  document.title = `You clicked ${count} times`;

You need to import useEffect and useState in order to use it.

useEffect removed the redundancy of writing the same code twice as we did in componentDidMount and componentDidUpdate methods.

Learn more on React Docs

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Angular 9 time clock update every minute, second, hourAngularHow to convert a function component into a class in React?ReactConfiguring Modules with @forward rule in SCSS (Sass)SCSSfirst-of-type and last-of-type selectors in CSSCSSWhat is a “promise” in JavaScript?JavaScriptA complete diagram with building blocks of an Angular applicationAngular