Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda