Home > Back-end >  Best practice regarding call to an API in React
Best practice regarding call to an API in React

Time:06-02

I'm bulding a simple movie app to train on React. I made a navigation menu where the user can click on movie categories as "popular", "now playing" to display different movies on the homepage.

My question is about how to handle the call to the API and what's considered the best practice. I thought about two solutions :

1 - call all the movies from all the categories using useEffect when the app loads for the first time and save all the movies in different useState separated by category.

const [popularMovies, setPopularMovies] = useState([])
const [nowPlayingMovies, setNowPlayingMovies] = useState([])
...

2 - create only one useState of moviesToDisplay and call the API and replace it's content every time the user click on a new category.

const [moviesToDisplay, setMoviesToDisplay] = useState([])

CodePudding user response:

Is better to only ask for the data you are going to display, if the user want to see a specific category and click for example a button "Horror" you fetch for the horror movies.

If you have a database with 500k movies, you are going to use a LOT of resources on every request, this is overkill in frontend and backend.

For your main page you can fetch a list of movies to display, like 10-15 movies, and also you can consider adding an infinite scroll, but allways fetch on demand.

User select category:

  • Horror => fetch horror movies => show movies
  • Action => fetch action movies => show movies
  • Related