how to set state array using react hooks how to set state array using react hooks reactjs reactjs

how to set state array using react hooks


To insert new element at the end of the list

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

To insert new element at the begining of the list

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


More readable and cleaner solution it would be:

Create a variable that holds a copy of the actual state:

If state is an array and you need to add an element in it

const newState = [...messages, 'Hi buddy'];setMessages(newState); orsetMessages(prevState => [...prevState, "Hi Buddy"]);

If state is an object and you need to update a property in it

const newState = Object.assign({}, message, {name: 'Michael Scott'});setMessages(newState);orsetMessages(prevState => {...prevState, name: "Michael Scott" });


There is no real need to use the prevState, you could just do:

setMessages([...messages, newMessage])