Roman Karpyshyn
Roman Karpyshyn

Reputation: 199

make setState in useEffect each time when screen appears

i have some useEffect function which works when component appeared at first time:

useEffect(() => {
    (async function () {
      try {
        console.log('works');
        const token = await AsyncStorage.getItem('token');
        if (token)
          setState({...state, isAuthorized: true})
      } catch (error) {
        console.log(error)
      }
    })();
  }, []);

But how to make it work every time without calling infinite loop, if i remove the empty array from the parameters?

Upvotes: 0

Views: 1259

Answers (2)

Benyamin
Benyamin

Reputation: 1144

You can pass the value as the second argument so it will be rendered when that value changes. for example:

useEffect(() => {}, [state])

Upvotes: 0

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

You have to mention the dependency array as the second parameter to useEffect() hook to tell React when you need the useEffect to run. The default case is that react will run useEffect on every component render/update.

So, if you are running into an infinite loop, its likely that your dependency array is not proper. You are essentially running into case where your useEffect will run, update something in your component, this will trigger a re-render, and then useEffect will run again and this cycle will keep repeating infinitely.

I don't think of any use case where you wouldn't mention the dependency array when you are using the useEffect hook. It would always be advisable to mention the list of dependencies as an array to the second parameter of useEffect hook or if there are no any dependencies, then you must pass an empty array. This should prevent infinite loop/re-renders from happening in your application.

Upvotes: 2

Related Questions