Lin Du
Lin Du

Reputation: 102207

Is it an anti-pattern to exit useEffect hook early?

In other words, add a conditional judgment to the useEffect hook to determine whether the execution of the effect is an anti-pattern.

Consider the following code:

import { useEffect } from 'react';

function useCustomEffect(dep) {

  const condition = complexCaculate(dep);

  useEffect(() => {
    if(!condition) return; // exit early
    // fetch API work. 
  }, [dep]);
}

function complexCaculate(dep) {
  // some complex caculation
}

I think if the condition is false, the callback of useEffect should not be executed.

Upvotes: 2

Views: 1326

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51756

No it's not an anti-pattern, but based on the existing code there's a slight improvement possible:

import { useEffect } from 'react';

function useCustomEffect(dep) {
  useEffect(() => {
    const condition = complexCaculate(dep);

    if(!condition) return; // exit early
    // fetch API work. 
  }, [dep]);
}

function complexCaculate(dep) {
  // some complex caculation
}

With this modification, complexCalculate() is only called whenever the effect is called, rather than every time the component in which useCustomEffect() is called is re-rendered.

Upvotes: 1

Related Questions