'React - prevent calling useEffect for the first mount [duplicate]
I want to prevent calling my useEffect
on the first mount
.
how can I do this?
I want the best practice
.
I don't want to use if condition
import { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(5);
useEffect(() => {
console.log(count);
}, [count]);
return (
<div>
<h1> Counter </h1>
<div> {count} </div>
<button onClick={() => setCount(count + 1)}> click to increase </button>
</div>
);
};
export default Counter;
Solution 1:[1]
I found it.
It should be handled by useLayoutEffect
and useRef
import { useState, useEffect, useLayoutEffect, useRef } from "react";
const Counter = () => {
const [count, setCount] = useState(5);
const firstUpdate = useRef(true);
useLayoutEffect(() => {
if (firstUpdate.current) {
firstUpdate.current = false;
return;
}
console.log(count);
});
return (
<div>
<h1> Counter </h1>
<div> {count} </div>
<button onClick={() => setCount(count + 1)}> click to increase </button>
</div>
);
};
export default Counter;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hossein fti |