showing results for - "usestate giving previously update data"
Vanessa
25 Feb 2017
1While React's setState is asynchronous (both classes and hooks), and it's 
2tempting to use that fact to explain the observed behavior, it is not the
3reason why it happens.
4
5TLDR: The reason is a closure scope around an immutable const value.
6
7Solutions:
8read the value in render function (not inside nested functions):
9
10useEffect(() => { setMovies(result) }, [])
11console.log(movies);
12
13add the variable into dependencies (and use the react-hooks/exhaustive-deps eslint rule):
14
15useEffect(() => { setMovies(result) }, [])
16useEffect(() => { console.log(movies) }, [movies])
17
18use a mutable reference (when the above is not possible):
19
20const moviesRef = useRef(initialValue)
21useEffect(() => {
22    moviesRef.current = result
23	console.log(moviesRef.current)
24}, [])