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

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
How to add recaptcha version 3 to PHP website?PHPHow to auto-resize textarea based on text input using JavaScript or jQuery?JavaScriptHow to add Read More Read Less Button using JavaScript?JavaScriptDefault Values in SCSS (Sass)SCSSWhat are Controlled Components in React?ReactHow to get the height and width of an element using JavaScript?JavaScript