Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
React - using hooks for data fetching and contexts for state management

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!