简体   繁体   中英

React useState in functional components not updating the property values immediately

The react useState hook is not updating the property value and displaying the old value even accessing it after sometime. I know that it is asynchronous update but eventually it should update the value. Here is my code:

const [ currentRowIndex, setCurrentRowIndex] = useState(0);
    React.useEffect(() => { 
        console.log('Index from useEffect: ',currentRowIndex);
        setCurrentRowIndex(currentRowIndex);}, [currentRowIndex]);
..
..
..
 const handleClick = (event, index) => {

        console.log('Index after click: ',index);
        setCurrentRowIndex(index);

        setTimeout(function(){ 
            console.log('Index in timeout: ',currentRowIndex);
         }, 3000);

        console.log('Index after updating: ',currentRowIndex);

    };

Output from the console:

Index after click:  4
Index after updating:  0
Index from useEffect:  4
Index in timeout:  0

console.log('Index after updating: ',currentRowIndex); this is giving 0 because it is not confirmed that when browser executing this state is already updated.

When you wann see the index value after updation completed then you just print index in useEffects with dependency list containing [currentRowIndex] then it shows you index is being updated properly.

if you can provide info what exactly you want to do with this updated value then it will help us to know the problem better.

Everything happens as it supposed to be, think about each time a components is rendered as a frame.

At the time you call handleClick the currentRowIndex is 0, you pass 0 to your setTimeout and you get 0 printed because that function remembers the currentRowIndex as 0 at this specific render, that function is not changed when the state updates.

If you render the currentRowIndex in a Text component you will see that it does update because the new render have the updated state.

You can print it outside of handleClick and see the state value on each render.

 console.log('Index: ',currentRowIndex);

 const handleClick = (event, index) => {
       ...
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM