I've searched for it but haven't found a definite answer to this question.
I have this component with states
function ChatWindow() {
const [messages, setMessages] = useState([])
const [newMessage, setNewMessage] = useState('')
function sendMessage(e) {
e.preventDefault();
messages.push(newMessage) // This
setNewMessage('')
}
function sendMessage2(e) {
e.preventDefault();
setMessages([...messages, newMessage]) // Vs this
setNewMessage('')
}
}
The sendMessage() and sendMessage2() are called via button of a form.
My question is that both of them work, so why should I even bother with using setMessages or there is a good reason for that?
I keep reading that we shouldn't modify state variables directly otherwise page/component won't rerender. But the messages on the front end get added fine both ways.
Help me out, please.