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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Object destructuring in JavaScript: Unpacking fields from objects passed as function parameterJavaScriptHow get_template_part helps write reusable code in WordPress?WordPressWHERE Clause in PostgresPostgresThe Difference Between isNaN() Method And isNaN() Function In JavaScriptJavaScriptHow to create Glowing Texts using CSS?CSSShort-Circuit Evaluation in JavaScriptJavaScript