Search code examples
reactjsreduxreact-reduxredux-thunk

React-Redux store or Passing the api in props to the components which is better way


I am just going through a confusion so far. I am developing a React application for that some amount of API call is required. so I just confused with whether calling the API in the component and passing the dats by props to the required components or Using redux thunk to fetch the api's and store in to a React store and fetching the required data by dispatching the action when ever it required.

Suggestions will be appreciable :)


Solution

  • Calling the API is surely gonna be done in the component. Like so:

    const Component = () => {
      useEffect(() => {
        const fn = async () => {
          await apiCall()
        }
        fn()
      }, [])
    }
    

    But your question resides on where you should store it.

    This is simple:

    1. If the data you are getting are gonna be used across the whole app, then Redux is a great option. It also comes with data persistence with very little effort using redux-persist (https://github.com/rt2zz/redux-persist) so it's not only to have a global object you can access.

    Features:

    a. Persistance b. Global state accesible anywere c. Enhanced debugging with Redux dev tools

    1. If you only want to avoid prop drilling then React.Context is a good option
    2. If you are only drilling 2 or 3 leves with your props, just don't overkill it using a Context