0

I am new to React and want to understand the difference from classic MVC. I want to create a simple components that loads some data initially and renders let say a grid. On some state or prop change it will reload the data and re-render.

What is the best approach in react from below two options?

  1. using the lifecycle events to load the data, update some state and render while in another event will show some loading opacity.

  2. Work with redux and react-redux? but in all example I cant see API calls. Is this the role of a middleware (Thunk?)?

Will appropriate an explanation.

1 Answer 1

2

Both the approaches are correct. It depends on your use case. If you can avoid using redux in your app, use the lifecycle methods to make API calls (also called subscriptions in react documentation). If you think your app has many components and different components needs to share a state, then use redux.

You should also look at React hooks https://reactjs.org/docs/hooks-reference.html You can use Effect Hook https://reactjs.org/docs/hooks-effect.html to make API calls and update your component's state.

Update:

Both Thunk and Sage are used to manage side effects in your application (making API calls from here). I've used saga, I don't know much about thunk.

How you would use redux-saga: Say if you want to get some data for display on a button click, this is how it works:

  • On button click you dispatch an action, say GET_DATA
  • Your redux reducer will change some state on this particular action, say isLoading=true
  • You can use isLoading in your component to show a spinner/overlay
  • At the same time saga will listen to GET_DATA action and make the API call
  • If success, from Saga you'll dispatch an action, say GET_DATA_SUCCESS with the data from API call
    • Reducer will change isLoading=false and set the data in state, say apiData = { ... }
  • If failure, from Saga you'll dispatch an action, say GET_DATA_FAILED with the error code/message
    • Reducer will change isLoading=false and set the error in state, say apiError = { ... }
  • You can now use isLoading=false in you component to remove spinner and display the data (apiData) or error (apiError) in you component.

You can go through this tutorial to learn more https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html

Sign up to request clarification or add additional context in comments.

3 Comments

Yes. Just saw the video on that from the react conf 2018 where they introduced hooks. Its just a way to do the same with functional components.
Can you however explain what Thunk is?
The explanation was too big for the comment. I've updated my answer with the explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.