Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use useEffect?

Tags:

reactjs

I'm currently looking at the react doc's example for useEffect

import React, { useState, useEffect } from 'react';  function Example() {   const [count, setCount] = useState(0);    // Similar to componentDidMount and componentDidUpdate:   useEffect(() => {     // Update the document title using the browser API     document.title = `You clicked ${count} times`;   });    return (     <div>       <p>You clicked {count} times</p>       <button onClick={() => setCount(count + 1)}>         Click me       </button>     </div>   ); }  

My question is that we can easily make a handleClick function for the button. We don't have to use useEffect

const handleButtonClick = () =>{ setCount(count+1) document.title = `You clicked ${count +1} times` }  <button onClick={handleButtonClick}/> 

So which way is considered good practice? Is it best to only use useEffect to trigger side effects that strictly couldn't be done along with the main effect(i.e when component receive new prop)

like image 671
Veryfreebird Avatar asked Jul 12 '19 08:07

Veryfreebird


People also ask

When would you use a useEffect?

The useEffect Hook allows you to perform side effects in your components. Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments. The second argument is optional.

Should I use useState or useEffect?

The useState hook is used for storing variables that are part of your application's state and will change as the user interacts with your website. The useEffect hook allows components to react to lifecycle events such as mounting to the DOM, re-rendering, and unmounting.

What is the benefit of useEffect?

Using useEffect is probably the best part of React Hooks. It helps reduce the clutter of the component lifecycle methods and, most importantly, it helps separate different logic that can appear in the lifecycle methods.


2 Answers

The idea to use useEffect hook is to execute code that needs happens during lifecycle of the component instead of on specific user interactions or DOM events.

For instance, you wish to set a timer that executes a code when the component is rendered initially or as done in your initial example, the document title is updated when the component mounts, there is no user interaction associated here

useEffect is an alternative for lifecycle method in class components in a functional component. It can be used to execute actions when the component mounts, or certain prop or state updated for component as well as to execute code when the component is about to unmount

like image 142
Shubham Khatri Avatar answered Sep 21 '22 10:09

Shubham Khatri


You showed two different examples,

handleButtonClick fires on Button 1 click, while useEffect fires on every state change state (according to the dependency array).

In the next example, you notice that useEffect will log on every button click (Button 1/2), and handleButtonClick will log only on Button 2 click.

import React, { useState, useEffect } from "react";  function Example() {   const [count, setCount] = useState(0);    useEffect(() => {     console.log(`You rendered ${count} times`);   }, [count]);    const handleButtonClick = () => {     setCount(count + 1);     console.log(`You clicked ${count + 1} times`);   };    return (     <div>       <p>You clicked {count} times</p>       <button onClick={() => setCount(count + 1)}>Button 1</button>       <button onClick={handleButtonClick}>Button 2</button>     </div>   ); } 
  • Check similar question on useEffect use cases
  • Refer to useEffect docs
like image 32
Dennis Vash Avatar answered Sep 20 '22 10:09

Dennis Vash