i cannot use previous value using useRef hook. previous value is equal to previous value. can someone tell me why?? and what is the solution.
i need to compare previous value of post;
const [selectedPost, setSelectedPost] = useState({ title: "", content: "" });
Following is previous value function
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
const prevVal = usePrevious(selectedPost);
Following is the function in which i use previous value
const handleClickUpdate = () => {
if (prevVal === selectedPost && isEmpty(errors))
return setEditClicked(false);
editPost(selectedPost, postId, "original", () => setEditClicked(false));
};
Edit//
i found out its happening because of this block of code. can someone explain why??
//clear validation errors on typing title or content
useEffect(() => {
if (!isEmpty(selectedPost.title) && !isEmpty(selectedPost.content))
dispatch(saveErrors({}));
}, [selectedPost, dispatch]);