React useState is not immediately updating the state of an array (react-native)

Active3 hr before
Viewed126 times

9 Answers


Much like setState in Class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.,If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn't have a callback pattern,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.

Even if you add a setTimeout the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout will still use the value from its previous closure and not the updated one.

console.log(movies) // movies here will not be updated

If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn't have a callback pattern

useEffect(() => {
   // action on update of movies
}, [movies]);

However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like

setMovies(prevMovies => ([...prevMovies, ...result]));
load more v

React this.setState, and useState does not make changes directly to the state object.,Does it feel like when you call this.setState or React.useState, the changes feel like it’s a step behind?,So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate.

If you’re using a class component, you will have to usethis.setState() to update the state of a React component.

this.setState(state, callback);
load more v

First, let's see how to use the useState() hook for creating an array state variable.,We destructure the return value of the useState() hook to get a variable that contains the state array and a method for updating the state.,In this article, we'll see by example how to update arrays via the React hook useState() using the push() method of the Array object.

import React from "react";

const {
} = React;

const [myArray, setMyArray] = useState([]);
load more v

Consider a functional component DoubleIncreaser:,this.setState(newState) updates this.state asynchronously.,When clicking Double Increase, does the component’s state update by 1 or 2?

import { useState } from 'react';

function DoubleIncreaser() {
  const [count, setCount] = useState(0);

  const doubleIncreaseHandler = () => {
    setCount(count + 1);    setCount(count + 1);  };

  return (
      <button onClick={doubleIncreaseHandler}>
        Double Increase
      <div>Count: {count}</div>
load more v

Think of setState() as a request to update the component. Reading state right after calling setState() a potential pitfall.,React hooks are now preferred for state management. Calling setState multiple times in one function can lead to unpredicted behavior read more.

 Pretag team - issue, fix, solve, resolve

React Hooks: Update state,Declaring state in React,How to update state in a nested object in React with Hooks

 Pretag team - issue, fix, solve, resolve

In a function component, we have no this, so we can’t assign or read this.state. Instead, we call the useState Hook directly inside our component:,In a function, we already have setCount and count as variables so we don’t need this:,Our new example starts by importing the useState Hook from React:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
load more v

Learn web development from expert teachers. Build real projects, join our community, and accelerate your career,While many engineers work at startups or are interested in starting their own company, venture capital can seem like a total mystery. In this episode, we talk about how venture capital firms function, how VCs make money - and...,The writing was over before I knew it, and we've sold way more copies than I expected! Plus, the compliments from my peers have been really amazing."

 Pretag team - issue, fix, solve, resolve

In order to update the array in the state object, a new array object must be supplied to the input key using the setState method:,This guide explains the steps to modify the state of a component using an array.,Note: In the above example, the list is updated as soon as you start typing because onChange updates the state that re-renders the App component.

1import React, { Component } from "react";
2import "./style.css";
4export default class App extends Component {
5  state = {
6    cart: ["Corn", "Potato"],
7  };
9  saveInput = (e) => {
10    this.setState({ input: });
11  };
13  addNewItem = () => {
14    let { cart, input } = this.state;
15    cart.push(input);
16    // this.state.cart.push(this.state.input); // same as above, though bad practice 
17  };
19  render() {
20    return (
21      <div>
22        <input
23          type="text"
24          onChange={this.saveInput}
25        />
26        <button onClick={this.addNewItem}> Add Item </button>
27        <ol>
28          {, sIndex) => {
29            return <li key={sIndex}> {subItems}</li>
30          })}
31        </ol>
32      </div>
33    );
34  }
load more v

Other "native-state" queries related to "React useState is not immediately updating the state of an array (react-native)"