简体   繁体   中英

Is it possible to only run useEffect on props change, but not state change?

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

  // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM