I have lms(learning management system) project using react and next js. I’m going to create a js file named apiFunctions and put all API caller function(using axios) in it and call these function each page I need and pass as props through children components. But I’m not sure this is the best way to connect API functions.
So I think of all existing options and I don’t know which one is the standard method:
1-calling API functions in each page and pass it to children component (just like I do).
2-creating context for each page and use in children by using provider.
3-creating context for each entity (for example: blogs,courses,… ) use in children by using provider.
4-using redux(or rtk) and put all caller functions as reducers and call the function we need in current page.
which solution is the best?
2
Answers
It depends on the scale of the project you are trying to create. If you are trying to create a relatively small project you can use
prop-drilling
as you can pass props from parent components to child components.If you are creating a relatively large project, it is better to use creating context for each of the pages as it helps to avoid prop-drilling.
If you are going for larger scale application with the ability to become it more larger, it is better to use something as Redux for state managing as you have lots of states to be managed.
You can use the react documentation to have an idea about this and also you can check this link for further more.
You can create a class for call API that called
Services
and put all methods of request in it like below.In your source it can be in
http.js
file for example.Then, use the
Services
in each component you want like this :For manage your data, it also depends on the scale of the project, you can use state managements like
Context
,Redux
.