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.

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]);

  // ...
}
16 users liked answer #0dislike answer #016
Tholle profile pic
Tholle

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).