Imagine that you have the following context
contexts/posts/UserPostsContext.js
const UserPostsContext = createContext(null);
export default UserPostsContext;
export function UserPostsProvider({ children }) {
const [posts, dispatch] = useReducer(userPostsReducer, initialState);
const addUserPosts = (userId, posts, unshift = false) => {
dispatch(actionCreators.addUserPosts(userId, posts, unshift));
};
const deleteUserPost = (userId, postId) => {
dispatch(actionCreators.deleteUserPost(userId, postId));
};
const getUserPosts = (userId) => posts[userId] ?? [];
return (
<UserPostsContext.Provider
value={{
addUserPosts,
deleteUserPost,
getUserPosts,
}}
>
{children}
</UserPostsContext.Provider>
);
}
Where you simply add/delete/get posts that have been fetched in a custom hook
useFetchUserPosts.js
const useFetchUserPosts = (() => {
const mutex = {};
const pagination = {};
const listeners = {};
return (userId) => {
const userPosts = useContext(UserPostsContext);
const posts = userPosts.getUserPosts(userId);
const [isLoading, setIsLoading] = useState(!posts.length);
...
const getMorePosts = async (limit = MAX_USER_POSTS_TO_RETRIEVE) => {
if (
mutex[userId]?.isFetching ||
pagination[userId]?.hasMoreToLoad === false ||
!isMounted()
) {
return;
}
...
const newPosts = await api.getUserPosts(userId);
userPosts.addUserPosts(userId, newPosts);
...
}
}
})();
My question is, as I take the delegation of responsibilities in the code very seriously in order to be as scalable and readable as possible, could the React Context API be used to fetch apis instead of hooks?
I mean, for me, contexts has the only functionality of "manage states" globally, and shouldn't be used to make API requests and stuff like that, but I have seen that is common in some people to delegate this part to the React Contexts.
Isn't this an anti-pattern or something like that?