append to useState array code example

Example 1: React Hooks append state

setTheArray(currentArray => [...currentArray, newElement])

Example 2: usestate array push

setTheArray([...theArray, newElement]);

Example 3: add items to a react array in hooks

const addMessage = (newMessage) => setMessages(state => [...state, newMessage])

Example 4: prepend to js array

var a = [1, 2, 3, 4];
a.unshift(0);
a; // => [0, 1, 2, 3, 4]

Example 5: add items to a react array in hooks

const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])

Tags:

Css Example