I want to use useEffect two times:
-when first-time component loaded
-when a specific value changed
how to implement both scenarios? best regards
CodePudding user response:
Simply by putting the value
into the useEffect
call's dependencies.
Since moving from "no value" (i.e. before mount) to having a value (at initial mount) is a change of value, it does the trick.
CodePudding user response:
enter a specific value in dep
useEffect(()=>{
},[anyValueState])
CodePudding user response:
Use that value in the state using useState
hook of react
and then pass it as the dependency to the useEffect
hook. It will first load the component and then load it whenever the dependency that is the value of the state is changed.
import React, { useState, useEffect } from 'react';
function Example() {
const [value, setValue] = useState(0);
useEffect(() => {
document.title = `You clicked ${value} times`;
});
return (
<div>
<p>You clicked {value} times</p>
<button onClick={() => setValue(value 1)}>
Click me
</button>
</div>
);
}
You can find the explanation of useEffect
and useState
in the docs: here