I created a hook, whose purpose is adding cherries to an array:
import { useReducer, useRef } from "react";
const useCherry = () => {
const myRef = useRef(0);
const [state, dispatch] = useReducer(
(state, action) => {
if (action.type === "add") {
myRef.current += 1;
return [...state, ""];
}
return state;
},
[]
);
return [state, dispatch, myRef];
};
export default useCherry;
Then I call it on button click:
<button
type="button"
onClick={() => {
console.log(myRef.current); // Logs 0
dispatch({ type: "add" });
console.log(myRef.current);// Logs 0, expected 1
}}
>
Add more cherry
</button>
I don't understand why would cherryRef.current return an old value after calling dispatchCherry(). In theory it should return the incremented one, as myRef is an object.
I'm trying to get the incremented value right after calling the dispatch().