This code runs when name is changed (as it should) but it also runs when the component first loads. How can I have it run only on subsequent changes to name and not the first time the default value is set?
const [name, setName] = useState('');
useEffect(() => {
alert('Hi ' + name);
}, [name]);
Using a ref you can track the first render, set to false after the first render.
const firstRenderRef = useRef(true);
const [name, setName] = useState('');
useEffect(() => {
if (firstRenderRef.current) {
firstRenderRef.current = false;
} else {
alert('Hi ' + name);
}
}, [name]);
I'd factor this into a custom hook though
const useSkipFirstEffect = (callback, dependencies) => {
const firstRenderRef = useRef(true);
useEffect(() => {
if (firstRenderRef.current) {
firstRenderRef.current = false;
} else {
callback();
}
}, [callback, ...dependencies]);
};
Usage:
useSkipFirstEffect(() => {
alert('SkipFirstEffect: Hi ' + name);
}, [name]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With