Answers for "usestate giving previously update data"

0

usestate giving previously update data

While React's setState is asynchronous (both classes and hooks), and it's 
tempting to use that fact to explain the observed behavior, it is not the
reason why it happens.

TLDR: The reason is a closure scope around an immutable const value.

Solutions:
read the value in render function (not inside nested functions):

useEffect(() => { setMovies(result) }, [])
console.log(movies);

add the variable into dependencies (and use the react-hooks/exhaustive-deps eslint rule):

useEffect(() => { setMovies(result) }, [])
useEffect(() => { console.log(movies) }, [movies])

use a mutable reference (when the above is not possible):

const moviesRef = useRef(initialValue)
useEffect(() => {
    moviesRef.current = result
	console.log(moviesRef.current)
}, [])
Posted by: Guest on September-07-2021

Code answers related to "usestate giving previously update data"

Code answers related to "Javascript"

Browse Popular Code Answers by Language