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 OverflowIf 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>;
}
TL;DR
useEffect(yourCallback, []) - will trigger the callback only after the first render.
Detailed explanation
useEffect runs by default after every render of the component (thus causing an effect).
When placing useEffect in your component you tell React you want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.
If you pass only a callback - the callback will run after each render.
If passing a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. for example when placing useEffect(() => console.log('hello'), [someVar, someOtherVar]) - the callback will run after the first render and after any render that one of someVar or someOtherVar are changed.
By passing the second argument an empty array, React will compare after each render the array and will see nothing was changed, thus calling the callback only after the first render.
Lets take an example - I want to initialize the SDK of a partner who will be loading an iframe on my page
-
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
-
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?
Hello all, i'm a fairly noob developper and new to react.
Is it possible to have a useEffect to only run when the dependency array changes and not at mount ?
Also i can't explain why but it seems to me a bad use of useEffect, is there a better way to achieve this ? Thanks
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?