I created a custom hook
const useMessageStorage = () => {
const [messages, setMessages] = useState([]);
const addMessages = (newMessage) => {
setMessages(oldMessages => [...oldMessages, newMessage)]);
}
const clear = () => {
setMessages([]);
}
return { clear, addMessages }
}
Inside the consumer component, I want to do something like
const { clear, addMessages } = useMessageStorage();
...
clear() // clear before adding new messages
addMessage('new message')
The above doesn't work because both calls are asynchronous. But I want to clear all messages before adding a new message in some specific scenario. How to tackle this problem? I considered using useRef but I'm afraid of using it because of race condition.