dots Created with Sketch.
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

amazon

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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
FETCH clause in PostgreSQLPostgresUnary Operators in JavaScriptJavaScriptUseful (and probably ignored) HTML tags: Part 1HTMLWhat happens when we add Numbers and Strings in JavaScript?JavaScriptHow to control file extensions with an .htaccess file?MiscellaneousHow does AdSense calculate page loading time?JavaScript