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

233
Views
Reaccionar: uso de ganchos para la obtención de datos y contextos para la gestión del estado

Imagina que tienes el siguiente contexto

contextos/mensajes/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> ); }

Donde simplemente agrega/elimina/obtiene publicaciones que se han obtenido en un gancho personalizado

usarFetchUserPosts.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); ... } } })();

Mi pregunta es, dado que me tomo muy en serio la delegación de responsabilidades en el código para que sea lo más escalable y legible posible, ¿podría usarse la API React Context para obtener apis en lugar de ganchos?

Quiero decir, para mí, contexts tiene la única funcionalidad de "administrar estados" globalmente, y no debe usarse para realizar solicitudes de API y cosas por el estilo, pero he visto que es común en algunas personas delegar esta parte a React. Contextos.

¿No es esto un anti-patrón o algo así?

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!