Morton
Morton

Reputation: 5760

How do I avoid trigger useEffect when I set the same state value?

I use react hook call an API and set the data to state and I still have some control view can change the value, but when I change it, my API function trigger again, it cause my view re render multiple times.

How do I use my fetchData function just like in class component componentDidMount function ?

const [brightness, setBrightness] = useState(0);

useEffect(() => {
  fetchData();
});

const fetchData = async () => {
  const value = await something();  // call API get the first value
  setBrightness(value);
};

return (
  <View>
    <SomeView value={brightness} onComplete={(value) => setBrightness(value)}
  </View>
);

Upvotes: 1

Views: 2692

Answers (1)

ug_
ug_

Reputation: 11440

Your useEffect will be triggered on every render because you haven't provided the 2nd argument.

The 2nd argument is what the effect is conditional upon. In your case you only want it to run once so you can provide an empty array.

useEffect(() => {
   // Run once
}, [])

Lets say you wanted it to fetch anytime some prop changed, you could write

useEffect(() => {
   // run every time props.myValue changes
}, [props.myValue])

See https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

Upvotes: 3

Related Questions