Home > Software design >  When should I use useEffect hook instead of event listeners?
When should I use useEffect hook instead of event listeners?

Time:05-18

Should useEffect hook be used when it can be simplified using an event listener?

For example, in the below snippet code I use event listener to change some state and later useEffect hook to react to that state change and do some other thing

import { useEffect, useState } from "react";

export default function Foo() {
  const [isActive, setIsActive] = useState(true);

  useEffect(() => {
    // do any kind of business logic
  }, [isActive]);

  return (
    <>
      <button
        type="button"
        className="secondary"
        onClick={() => setIsActive(true)}
      >
        ACTIVATE
      </button>
      <button
        type="button"
        className="secondary"
        onClick={() => setIsActive(false)}
      >
        DEACTIVATE
      </button>
    </>
  );
}

Should I move useEffect logic to the onClick listeners?

CodePudding user response:

The beta docs advise to perform side effects in event handlers when possible, here is quote from docs:

In React, side effects usually belong inside event handlers. Event handlers are functions that React runs when you perform some action—for example, when you click a button. Even though event handlers are defined inside your component, they don’t run during rendering! So event handlers don’t need to be pure.

If you’ve exhausted all other options and can’t find the right event handler for your side effect, you can still attach it to your returned JSX with a useEffect call in your component. This tells React to execute it later, after rendering, when side effects are allowed. However, this approach should be your last resort.

Also related quote by Dan Abramov:

To sum up, if something happens because a user did something, useEffect might not be the best tool.

On the other hand, if an effect merely synchronizes something (Google Map coordinates on a widget) to the current state, useEffect is a good tool. And it can safely over-fire.

CodePudding user response:

UseEffect run once when the component does mounting.

You can have state that triger the useEffect .

Should You move useEffect logic to the onClick listeners?

That depend on you, if you need to render your app , so no.

onClick function need do to something that depend to the page logic.

CodePudding user response:

You don't need useEffect for simple operations, useEffect will also call on the component mount that you have to handle.

export default function Foo() {
  const onClick = useCallback((isActive) => {
    // fetch some data
    // set that data to state
  }, []);

  return (
    <>
      <button type="button" className="secondary" onClick={() => onClick(true)}>
        ACTIVATE
      </button>
      <button
        type="button"
        className="secondary"
        onClick={() => onClick(false)}
      >
        DEACTIVATE
      </button>
    </>
  );
}
  • Related