[javascript] Push method in React Hooks (useState)?

How to push element inside useState array React hook? Is that as an old method in react state? Or something new?

E.g. setState push example ?

This question is related to javascript reactjs react-hooks

The answer is

// Save search term state to React Hooks with spread operator and wrapper function

// Using .concat(), no wrapper function (not recommended)

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])


setTheArray([...theArray, newElement]); is the simplest answer but be careful for the mutation of items in theArray. Use deep cloning of array items.

I tried the above methods for pushing an object into an array of objects in useState but had the following error when using TypeScript:

Type 'TxBacklog[] | undefined' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)

The setup for the tsconfig.json was apparently right:

   "compilerOptions": {
   "target": "es6",
   "lib": [

This workaround solved the problem (my sample code):


   interface TxBacklog {
      status: string,
      txHash: string,

State variable:

    const [txBacklog, setTxBacklog] = React.useState<TxBacklog[]>();

Push new object into array:

    // Define new object to be added
    const newTx = {
       txHash: '0x368eb7269eb88ba86..',
       status: 'pending'
    // Push new object into array
       ? setTxBacklog(prevState => [ ...prevState!, newTx ])
       : setTxBacklog([newTx]);

if you want to push after specific index you can do as below:

   const handleAddAfterIndex = index => {
       setTheArray(oldItems => {
            const copyItems = [...oldItems];
            const finalItems = [];
            for (let i = 0; i < copyItems.length; i += 1) {
                if (i === index) {
                } else {
            return finalItems;

Most recommended method is using wrapper function and spread operator together. For example, if you have initialized a state called name like this,

const [names, setNames] = useState([])

You can push to this array like this,

setNames(names => [...names, newName])

Hope that helps.

The same way you do it with "normal" state in React class components.


function App() {
  const [state, setState] = useState([]);

  return (
      <p>You clicked {state.join(" and ")}</p>
      <button onClick={() => setState([...state, "again"])}>Click me</button>
      //old way
      <button onClick={() => setState(state.concat("again"))}>Click me</button>

To expand a little further, here are some common examples. Starting with:

const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);

Push element at end of array

setTheArray(prevArray => [...prevArray, newValue])

Push/update element at end of object

setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));

Push/update element at end of array of objects

setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);

Push element at end of object of arrays

let specificArrayInObject = theObject.array.slice();
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };

Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u

You can append array of Data at the end of custom state:

  const [vehicleData, setVehicleData] = React.useState<any[]>([]);
  setVehicleData(old => [...old, ...newArrayData]);

For example, In below, you appear an example of axios:

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
          url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
          method: 'get',
      setVehicleData(old => [...old, ...result.data.data]);

  }, [page]);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-hooks

Invalid hook call. Hooks can only be called inside of the body of a function component React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? react hooks useEffect() cleanup for only componentWillUnmount? How to use callback with useState hook in react Push method in React Hooks (useState)? React Hooks useState() with Object useState set method not reflecting change immediately React hooks useState Array Can I set state inside a useEffect hook