Search code examples
reactjsdatabasereduxdatabase-connectiondatabase-performance

Shall I fetch data from database each time a page of my website loads or use redux?


I have a react app that contains the following pages:

  1. /articles - shows different articles posted by all users

  2. /friends - shows all my friends

  3. /history - shows my activity history

I have a question regarding connection with databases.

Shall I connect with database each time a user navigates to individual routes to display data

OR

Shall I connect with database first time user navigates to the page and store it in redux store so that when next time the user routes to same path I can check redux store before connecting to database to retrieve data.

ps: every time the database data changes (such as: someone posts a new post, I got a new friend, or my activity history changes) I shall be updating redux store.

I thought storing in redux would give better performance as it would minimize load on database but

Would using redux store much slow down the user's computer?

Are these approaches justifiable?

If yes Which one is better in what situations?


Solution

  • you connect to database only once when you open the application, then each time you update data in your database you dispatch an action with redux

    for example:

    in the articles component

      const articles = useSelector((state) => state.articles );
    

    this component will render ech time the value of state.articles change, and this last changes when you dispatch an action

    so you will get always the new version of articles