If you only want to run the function given to useEffect after the initial render, you can give it an empty array as second argument.

function MyComponent() {
  useEffect(() => {
    loadDataOnlyOnce();
  }, []);

  return <div> {/* ... */} </div>;
}
Answer from Tholle on Stack Overflow
🌐
React
legacy.reactjs.org › docs › hooks-effect.html
Using the Effect Hook – React
If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.
🌐
Reddit
reddit.com › r/reactjs › what is the best way to execute a piece of code just once when the component mounts?
r/reactjs on Reddit: What is the best way to execute a piece of code just once when the component mounts?
January 26, 2024 -

Lets take an example - I want to initialize the SDK of a partner who will be loading an iframe on my page

  1. I can use a `useEffect` with empty dependency array. It will work fine in production but will be fired twice in development mode. And that does not feel right

  2. I can use `useRef` and base my logic around it, But this does not look intuitive either.

What would be the best way to do this?

🌐
Josh Software
blog.joshsoftware.com › 2021 › 08 › 09 › react-tricks-customizing-your-useeffect-to-run-only-when-you-want
React Tricks: Customizing your useEffect to run ONLY when you want! – Josh Software
July 22, 2022 - That’s why “Starting of ... That means, even when the component state changes, useEffects run only after the component has executed the return statement....
🌐
CSS-Tricks
css-tricks.com › run-useeffect-only-once
Run useEffect Only Once | CSS-Tricks
July 30, 2019 - To run componentWillUnmount just once, you return a cleanup function from useEffect and pass an empty array as the second parameter too. I’ve been converting some of my codebases to Hooks, and it’s getting pretty fascinating.
🌐
Robin Wieruch
robinwieruch.de › react-useeffect-only-once
React useEffect only Once - Robin Wieruch
November 7, 2020 - import * as React from 'react'; const App = () => { const [toggle, setToggle] = React.useState(true); const handleToggle = () => { setToggle(!toggle); }; const calledOnce = React.useRef(false); React.useEffect(() => { if (calledOnce.current) { return; } if (toggle === false) { console.log('I run only once if toggle is false.'); calledOnce.current = true; } }, [toggle]); return ( <div> <button type="button" onClick={handleToggle}> Toggle </button> {toggle && <div>Hello React</div>} </div> ); }; export default App; If you want to have a reusable custom hook for it, which only triggers the effect function once (and not on mount), you can use the following hook for it:
🌐
GitHub
github.com › unixzii › use-mount-effect
GitHub - unixzii/use-mount-effect: A hook triggered only once on mount.
import { useMountEffect } from "use-mount-effect"; const MyComponent = () => { useMountEffect(() => { // Do something only when the component mounts. return () => { // Do something only when the component unmounts. }; }); return <div>Blah blah blah</div>; }; Actually, you don't need to use this hook in production mode, because it behaves just like useEffect.
Author   unixzii
Find elsewhere
🌐
DEV Community
dev.to › esedev › useeffect-vs-useeffectonce-2cnk
useEffect vs useEffectOnce - DEV Community
March 8, 2023 - While useEffect is a great general-purpose tool, there are cases where you only need to execute a side effect once, when the component is mounted.
🌐
Reddit
reddit.com › r/reactjs › why is this useeffect hook called?
r/reactjs on Reddit: why is this useEffect hook called?
March 28, 2024 -
const TestComponent = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);

useEffect(() => {
    console.log("Only run if isLoggedIn changes");
}, [isLoggedIn]);

return (
    <div>
        <h1>Test Component</h1>
    </div>
);

};

export default TestComponent;

surely it's only meant to execute when isLoggedIn changes?

🌐
React
react.dev › reference › react › useEffect
useEffect – React
See common solutions. Try to write every Effect as an independent process and think about a single setup/cleanup cycle at a time. It shouldn’t matter whether your component is mounting, updating, or unmounting.
🌐
TypeOfNaN
typeofnan.dev › how-to-prevent-useeffect-from-running-on-mount-in-react
How to prevent useEffect from running on mount in React | TypeOfNaN
In this case, we’ll create a ref to a boolean that tracks whether the component has mounted. It will start out as false, but once the effect runs for the first time, we can change it to true. This is probably much easier to understand as code: function MyComponent() { const [data, setData] = useState(); const isMounted = useRef(false); // An effect to fetch the data useEffect(() => { fetch('/api/some-api') .then((res) => res.json()) .then((d) => { setData(d); }); }, []); // Do something else with the data useEffect(() => { if (isMounted.current) { doSomething(data); } else { isMounted.current = true; } }, [data]); }
🌐
usehooks-ts
usehooks-ts.com › react-hook › use-effect-once
useEffectOnce
useEffectOnce: Unnecessary abstraction, prefer built-in React hooks. useUpdateEffect: Unnecessary abstraction, prefer built-in React hooks. useImageOnLoad: Too opinionated. Some hook signature have been updated introducing breaking changes. ...
🌐
Perssondennis
perssondennis.com › articles › react-hook-use-run-once
Persson Dennis - React Hook: useRunOnce | Web Development Blog
July 17, 2022 - Simply place the code in a file right above a React component and it will run once and only once, that's how ES6 modules are designed. See examples of when not to use an useEffect in Reacts documentation.
🌐
Medium
medium.com › @reactcompany01 › how-to-call-loading-function-with-react-useeffect-only-once-e5fdbd598ec8
How to Call Loading Function with React UseEffect Only Once | by Reactcompany | Medium
March 27, 2023 - Hook acquires two arguments: the first argument passed to useEffect is a function, and the second argument is an array of dependency. ... The function runs once following component mount for a pattern that validates react hook practice. On ...
🌐
Dave Ceddia
daveceddia.com › useeffect-hook-examples
How the useEffect Hook Works (with Examples)
October 22, 2020 - So, even though we’re passing [inputRef] as the 2nd argument of useEffect, it will effectively only run once, on initial mount.
🌐
DhiWise
dhiwise.com › post › how-to-make-useeffect-run-only-once-for-optimal
How to Make useEffect Run Only Once for React
October 25, 2024 - To ensure that useEffect runs only once and mimics the behavior of componentDidMount, you can pass an empty array as the second argument. Passing an empty array ensures the effect runs only once during the initial render cycle.
🌐
O'Reilly
oreilly.com › library › view › learn-react-hooks › 9781838641443 › af55a148-6262-4517-8806-ce7fcdda5ad0.xhtml
Trigger effect only on mount - Learn React Hooks [Book]
October 18, 2019 - If we want to replicate the behavior ... second argument to the useEffect Hook: ... Passing an empty array means that our effect function will only trigger once when the component mounts, and it will not trigger when props ...
Author   Daniel Bugl
Published   2019
Pages   426
🌐
DEV Community
dev.to › ssharish › run-useeffect-only-once-react-57go › comments
[Discussion] Run useEffect Only Once :React — DEV Community
February 13, 2020 - If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.