-1

When I use useEffect with hooks inside it does not update state:

const App = () => {
    const [isLoading, setLoading] = useState(false);
    useEffect(() => { 
       Alert.alert('Before setLoading: ' + isLoading);
       setLoading(true);
       Alert.alert('After setLoading: ' + isLoading);
    }, []);
  ...
}

Both times it alerts:
Before setLoading: false
After setLoading: false

Can you please suggest why it behaves this way?

Shukhrat Raimov
  • 2,137
  • 4
  • 21
  • 27

2 Answers2

0

when you setState in useEffect, it doesn't update immediately. it's happening because of this reason

Alternative Way

you can use useRef instead of useState

const isLoading = useRef(false);
useEffect(() => { 
      console.log(isLoading.current) // isLoading is false
      isLoading.current = true
      console.log(isLoading.current) // isLoading is true
}, []);
Kaveh Karami
  • 335
  • 1
  • 4
  • 14
0

setState is asynchronous, the state update only take effect at the next render

to see the value of isLoading at the next render, do this

const App = () => {
    const [isLoading, setLoading] = useState(false);

    useEffect(() => {
       Alert.alert('Before setLoading: ' + isLoading) 
       setLoading(true);
    }, []);
    
    useEffect(() => { 
       Alert.alert('After setLoading: ' + isLoading);
    }, [isLoading]);
}
Acid Coder
  • 2,047
  • 15
  • 21