Based on @ford04 comments, I could use a conditional dependency on useEffect

It however goes at the cost of having a warning

** In this example it doesn't feel logical to execute always the hook without an access being granted, but its only use is to show that a conditional dependency in useEffect is possible (which I didn't know)

import React, { useEffect, useState, createContext, useContext } from "react";
import "./styles.css";

const AuthContext = createContext(null);
const useAuth = () => useContext(AuthContext);
const useAuthProvider = () => {
  const [access, setAccess] = useState(0);
  return { access, setAccess };
};

const useExample = withoutAuth => {
  const auth = useAuth();
  const [content, setContent] = useState("");

  useEffect(() => {
    console.log(auth);
    console.log(!withoutAuth);
    if (auth && !auth.access && !withoutAuth) return;
    setContent("fetched content");
    console.log("done"); // this is executed always, regardless of auth

    // even uselesser code
  }, [withoutAuth ? null : auth]);

  return [content];
};

const Button = () => {
  const auth = useAuth();
  return (
    <button
      onClick={() => {
        auth.setAccess(1);
      }}
    >
      Fetch
    </button>
  );
};

const Content = () => {
  const auth = useAuth();
  const [content] = useExample(1); // here I say NOT to implement auth
  return <h2>{(auth && auth.access && content) || "restricted"}</h2>;
};

export default function App() {
  const authProvider = useAuthProvider();

  return (
    <AuthContext.Provider value={authProvider}>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <Button />
        <Content />
      </div>
    </AuthContext.Provider>
  );
}

https://codesandbox.io/s/competent-currying-jcenj?file=/src/App.js

Answer from GWorking on Stack Overflow
๐ŸŒ
DEV Community
dev.to โ€บ rangeoshun โ€บ optimize-useeffect-by-using-the-condition-itself-as-a-dependency-1c2j
Optimize useEffect by using a condition as a dependency - DEV Community
April 3, 2020 - You cannot conditionally call useEffect or any other hook for that matter. In these cases, you add the condition in the function performing the side effect itself, while the variables checked in the condition go into the dependency array.
Top answer
1 of 1
4

Based on @ford04 comments, I could use a conditional dependency on useEffect

It however goes at the cost of having a warning

** In this example it doesn't feel logical to execute always the hook without an access being granted, but its only use is to show that a conditional dependency in useEffect is possible (which I didn't know)

import React, { useEffect, useState, createContext, useContext } from "react";
import "./styles.css";

const AuthContext = createContext(null);
const useAuth = () => useContext(AuthContext);
const useAuthProvider = () => {
  const [access, setAccess] = useState(0);
  return { access, setAccess };
};

const useExample = withoutAuth => {
  const auth = useAuth();
  const [content, setContent] = useState("");

  useEffect(() => {
    console.log(auth);
    console.log(!withoutAuth);
    if (auth && !auth.access && !withoutAuth) return;
    setContent("fetched content");
    console.log("done"); // this is executed always, regardless of auth

    // even uselesser code
  }, [withoutAuth ? null : auth]);

  return [content];
};

const Button = () => {
  const auth = useAuth();
  return (
    <button
      onClick={() => {
        auth.setAccess(1);
      }}
    >
      Fetch
    </button>
  );
};

const Content = () => {
  const auth = useAuth();
  const [content] = useExample(1); // here I say NOT to implement auth
  return <h2>{(auth && auth.access && content) || "restricted"}</h2>;
};

export default function App() {
  const authProvider = useAuthProvider();

  return (
    <AuthContext.Provider value={authProvider}>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <Button />
        <Content />
      </div>
    </AuthContext.Provider>
  );
}

https://codesandbox.io/s/competent-currying-jcenj?file=/src/App.js

People also ask

Why is the dependency array important in useEffect?
The dependency array in useEffect tells React when to re-run the effect. It ensures the effect only runs when specified state or prop values change, improving performance and avoiding unnecessary renders.
๐ŸŒ
dhiwise.com
dhiwise.com โ€บ post โ€บ understanding-the-importance-of-the-useeffect-dependency-array-in-react
UseEffect Dependency Array
Can you use objects or arrays in the useEffect dependency array?
Yes, but JavaScript compares object or array references, not their contents. This can cause unnecessary re-renders. To avoid this, use the useMemo hook to memoize objects or arrays used in the dependency array.
๐ŸŒ
dhiwise.com
dhiwise.com โ€บ post โ€บ understanding-the-importance-of-the-useeffect-dependency-array-in-react
UseEffect Dependency Array
What happens if you donโ€™t pass a dependency array to useEffect?
Without a dependency array, the effect runs after every render. This can lead to performance issues and bugs since the effect won't re-run based on changes in specific dependencies.
๐ŸŒ
dhiwise.com
dhiwise.com โ€บ post โ€บ understanding-the-importance-of-the-useeffect-dependency-array-in-react
UseEffect Dependency Array
๐ŸŒ
React
react.dev โ€บ reference โ€บ react โ€บ useEffect
useEffect โ€“ React
If you omit this argument, your Effect will re-run after every commit of the component. See the difference between passing an array of dependencies, an empty array, and no dependencies at all. ... useEffect is a Hook, so you can only call it at the top level of your component or your own Hooks. You canโ€™t call it inside loops or conditions.
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ is it ok to use a conditional as a useeffect dependency?
r/reactjs on Reddit: Is it OK to use a conditional as a useEffect dependency?
January 15, 2024 -

Is this ok? Specifically using totalUniqueItems === 0 as a useEffect dependency?

useEffect(() => { 
    setFinanceOptions({ 
        depositPercent: 10, 
        depositAmount: 0, 
        totalFinanceCost: 0, 
        financeCostPerMonth: 0, 
        interest: 17.9, 
        term: 36, 
        items: [], 
}); }, [totalUniqueItems === 0, setFinanceOptions]);

๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ useeffect conditional dependency arrays... but???
r/reactjs on Reddit: useEffect conditional dependency arrays... but???
April 1, 2022 -

Okay I read about this somewhere... I wish I could give credit where it's due.

But you build a conditional outside your useEffect... for cleanliness... and then put that in the useEffect dep array.

See attached image.

I am finding my useEffect runs regardless of the conditional... which maybe I need to state in the dependency array... conditional === true...

Dang as I type this... that is probably my problem. But I'll lean it here incase anybody else has not see something like this before.

https://www.instagram.com/p/Cb04lovOFOV/

Sorry for the instagram drop.. but apparently the reddit react doesn't let images to be uploaded. And I'm too lazy to open VS code and copy the code again. Sorry!

๐ŸŒ
GitHub
github.com โ€บ alexkrolick โ€บ use-conditional-effect
GitHub - alexkrolick/use-conditional-effect: React.useEffect, except you can pass a comparison function.
Additionally, dependencies doesn't have to be an array, it can be an object or any other value. ... This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies: ... You use it in ...
Starred by 111 users
Forked by 2 users
Languages ย  JavaScript 100.0% | JavaScript 100.0%
๐ŸŒ
Medium
medium.com โ€บ @nagireddygajjela19 โ€บ mastering-conditional-execution-of-effects-in-react-with-useeffect-a62dc86f4e72
8. Mastering Conditional Execution of Effects in React with useEffect | by NagiReddy Gajjela | Medium
October 22, 2023 - Conditional Execution: With the useEffect hook in React, you have the ability to conditionally execute an effect. Dependency Array: This condition is determined by the second parameter, which is an array known as the โ€œdependency array.โ€
Find elsewhere
๐ŸŒ
Bitstack
blog.bitsrc.io โ€บ understanding-dependencies-in-useeffect-7afd4df37c96
Understanding Dependencies in useEffect | Bits and Pieces
March 4, 2025 - Rows indicate when the effect should run, columns show the actual dependencies of the effect, and cells specify the array of dependencies to be used when calling useEffect.
๐ŸŒ
DhiWise
dhiwise.com โ€บ post โ€บ understanding-the-importance-of-the-useeffect-dependency-array-in-react
UseEffect Dependency Array
August 13, 2025 - This helps you visualize how React decides whether to run the useEffect callback function. Understanding this flow makes it easier to avoid unnecessary re executions. The React hooks exhaustive deps ESLint rule warns when your effect uses variables not listed in the dependency array.
Top answer
1 of 7
195

You can pass JSON.stringify(outcomes) as the dependency list:

Read more here

useEffect(() => {
  console.log(outcomes)
}, [JSON.stringify(outcomes)])
2 of 7
23

Using JSON.stringify() or any deep comparison methods may be inefficient, if you know ahead the shape of the object, you can write your own effect hook that triggers the callback based on the result of your custom equality function.

useEffect works by checking if each value in the dependency array is the same instance with the one in the previous render and executes the callback if one of them is not. So we just need to keep the instance of the data we're interested in using useRef and only assign a new one if the custom equality check return false to trigger the effect.

function arrayEqual(a1: any[], a2: any[]) {
  if (a1.length !== a2.length) return false;
  for (let i = 0; i < a1.length; i++) {
    if (a1[i] !== a2[i]) {
      return false;
    }
  }
  return true;
}

type MaybeCleanUpFn = void | (() => void);

function useNumberArrayEffect(cb: () => MaybeCleanUpFn, deps: number[]) {
  const ref = useRef<number[]>(deps);

  if (!arrayEqual(deps, ref.current)) {
    ref.current = deps;
  }

  useEffect(cb, [ref.current]);
}

Usage

function Child({ arr }: { arr: number[] }) {
  useNumberArrayEffect(() => {
    console.log("run effect", JSON.stringify(arr));
  }, arr);

  return <pre>{JSON.stringify(arr)}</pre>;
}

Taking one step further, we can also reuse the hook by creating an effect hook that accepts a custom equality function.

type MaybeCleanUpFn = void | (() => void);
type EqualityFn = (a: DependencyList, b: DependencyList) => boolean;

function useCustomEffect(
  cb: () => MaybeCleanUpFn,
  deps: DependencyList,
  equal?: EqualityFn
) {
  const ref = useRef<DependencyList>(deps);

  if (!equal || !equal(deps, ref.current)) {
    ref.current = deps;
  }

  useEffect(cb, [ref.current]);
}

Usage

useCustomEffect(
  () => {
    console.log("run custom effect", JSON.stringify(arr));
  },
  [arr],
  (a, b) => arrayEqual(a[0], b[0])
);

Live Demo

๐ŸŒ
Medium
egebilge.medium.com โ€บ best-practices-for-useeffect-dependency-arrays-in-react-fcb53ef55495
๐ŸŽฏ Best Practices for useEffect Dependency Arrays in React | by Ege Bilge | Medium
April 24, 2025 - In React, the useEffect hook runs after the component mounts and whenever any value in its dependency array changes:
๐ŸŒ
Reacttraining
reacttraining.com โ€บ blog โ€บ when-to-use-functions-in-hooks-dependency-array
When do I use functions in a Hooks Dependency Array?
September 30, 2019 - The parent function could experience re-renders that would cause ComposeMessage to re-render. When it does, the dependency array of the useEffect will be re-evaluated. In cases where the parent re-renders but doesn't change the uid, we want to ensure that the saveToLocalStorage function doesn't change so that way the effect doesn't run.
๐ŸŒ
React
react.wiki โ€บ home โ€บ react hooks โ€บ useeffect dependency array: deep mechanics explained
useEffect Dependency Array: Deep Mechanics Explained | react.wiki
January 1, 2026 - After each render, React compares the new dependency array with the previous one, element by element, using strict equality. ... function UserProfile({ userId }: { userId: number }) { const [user, setUser] = useState(null); useEffect(() => { fetchUser(userId).then(data => setUser(data)); }, [userId]); // โ† Dependency array return <div>{user?.name}</div>; }
๐ŸŒ
egghead.io
egghead.io โ€บ lessons โ€บ react-manage-the-useeffect-dependency-array
Manage the useEffect dependency array | egghead.io
This normally wonโ€™t lead to bugs (in fact, it does a great job at preventing bugs that plagued React apps before useEffect was available), but it can definitely be sub-optimal (and in some cases can result in an infinite loop). In this lesson weโ€™ll observe that our effect callback is getting called more than it needs to be, and youโ€™ll learn how to add a dependency array so it is updated only when the state it relies on changes.
Published ย  March 10, 2020
๐ŸŒ
Theodo
apps.theodo.com โ€บ en โ€บ article โ€บ how-to-avoid-bugs-in-useeffect
How to manage the useEffect dependency array like a pro?
March 1, 2022 - There is a dependency array to control when the effect should run. It runs when the component is mounted and when it is re-rendered while a dependency of the useEffect has changed.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ reactjs โ€บ what-are-the-dependencies-in-useeffect-and-why-are-they-important
What are the dependencies in useEffect and why are they important? - GeeksforGeeks
July 23, 2025 - The dependencies array allows you to specify which values the effect depends on. If any of these values change, the effect will be re-run. Optimizes performance by running the effect only when necessary.
๐ŸŒ
Medium
medium.com โ€บ @mircea.calugaru โ€บ optimization-with-useeffect-hook-conditional-firing-8670a2a61a35
Optimization with useEffect Hook: Conditional Firing | by Mike Calugaru | Medium
March 21, 2020 - That way an effect is always recreated if one of its dependencies changesโ€. By passing โ€œa second argument to useEffect that is the array of values that the effect depends onโ€ you can surgically control when the effect is fired.
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ can someone explain useeffect dependency arrays like im 5?
r/reactjs on Reddit: Can someone explain useEffect dependency arrays like im 5?
April 24, 2022 -

When do you need to use it? Why do I need to put a empty array even though its empty? When would I put something in the empty array?

Sorry if stupid noob question.