I have a reducer in my useMessages()
hook. For simplicity, let's focus on the "add"
action of my reducer, which just adds a message to an array of messages and assigns an incrementing ID to it:
import { useReducer, useRef } from "react";
const useMessages = () => {
const localMessageId = useRef(1);
const [messages, dispatchMessages] = useReducer(
(messages, action) => {
switch (action.type) {
case "add":
return [
...messages,
{
...action.message,
id: action.message.id ?? localMessageId.current++,
},
];
// Other actions
}
},
[]
);
return [messages, dispatchMessages, localMessageId.current];
};
export default useMessages;
The problem is that in Strict Mode, my ID is incremented twice, so the first message gets the ID of 2. I need to use the newly created ID after adding the message, but I'm not sure how to get this ID.
Is updating a useRef()
value in a reducer even considered valid in React? I know that we're not supposed to run side effects in reducers, memo etc.