Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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.

like image 982
Thjen Avatar asked Mar 21 '19 16:03

Thjen


People also ask

Does useEffect run when props change?

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

Does useEffect run on state change?

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.

Does useEffect always run on first render?

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.

Is useEffect always called on Mount?

Important: the useEffect hook will always run on mount regardless of if there is anything in its dependency array.


1 Answers

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

  // ...
}
like image 158
Tholle Avatar answered Sep 20 '22 12:09

Tholle