as the title suggests, I'm trying to make a useEffect only run on props change, but not if I change state (or specifically it should not run when I run useState).
The reason for this, is that I have user inputs, that defaults to an input stored in a database, but is fetched on mount, but CAN change if props change.
useEffect(() => {
let userTags = [];
props.question.tagVotes.forEach((tagVote) => {
if (_.includes(tagVote.users, props.user.username)) {
userTags.push(tagVote.tag);
}
});
setChosenTags(userTags);
});
Is it possible? Thanks.
Just like the state, we can also use props as a dependency to run the side effect. In this case, the side effect will run every time there is a change to the props passed as a dependency. useEffect(() => { // Side Effect }, [props]);
Use the useEffect hook to listen for state changes in React. You can add the state variables you want to track to the hook's dependencies array and the logic in your useEffect hook will run every time the state variables change.
Before using useEffect hook, you need to know exactly when the component will be (re)rendered, as effects are executed after each rendering cycle. Effects are always run after rendering, but there is an option to opt out of this behavior.
Important: the useEffect hook will always run on mount regardless of if there is anything in its dependency array.
The function given as first argument to useEffect
will run every time any of the elements in the array given as second argument change, so you can put the props in this array to make it run again when any of the props change.
Example
function App(props) {
useEffect(() => {
let userTags = [];
props.question.tagVotes.forEach(tagVote => {
if (_.includes(tagVote.users, props.user.username)) {
userTags.push(tagVote.tag);
}
});
setChosenTags(userTags);
}, [props.question]);
// ...
}
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