Reputation: 305
I am developing a React Js project which requires multiple states, with each state storing multiple json data from different backend endpoints. For Example, one of my component goes like:
Class Demo{
constructor(){
super();
this.state={
data1:[],
data2:[], .... so on
}
}
function() {
let somevar1 = axios.get('https://url');
let somevar2 = axios.get('https://url');
}
this.setState({
data1: somevar1,
data2: somevar2,
...and so on
})
}
The states are increasing as data is increasing.
I am new to react hence following this approach to store states independently in multiple components. might be slowing down my application for now. Please suggest me the better approach to handle these types of multiple states. Should I be using Redux or Hooks or Context API?
Upvotes: 0
Views: 2764
Reputation: 295
It is not a good practice to store a large state in different component. I'd suggest you to use redux where you can maintain your state in just one store. It is what we call single source of truth
https://react-redux.js.org/introduction/quick-start
Upvotes: 0
Reputation: 8418
You can use redux - reliable, stable solution ... but it has many drawbacks - goodbye-redux article.
Try Apollo (graphql client with normalizing cache) with apollo-link-rest. You can then use multiple endpoints. All data will be available using one common method (local app data, too).
Later you can setup a graphql server to create one common endpoint with almost no change to frontend app.
You can use both (redux for global app state + apollo for all data and some settings) - apollo-universal-starter-kit demonstrates this possibility.
Upvotes: 0
Reputation: 1938
State is a property which is bounded to a particular component. If you require multiple states this means you need multiple components,as you can just have one state per component.
So you need to figure out which endpoints need to be called and from which components.
Usually, there is no limit of data that can be stored in a state, but as the component will destroy, all the data(state) of its will lost. So here comes the part of redux which can store the state globally, and this state can be mapped to props in the components which need them.
On the information which you have provided it seems redux will be a good option option for this use case as you can create reducers and separate state from one endpoint to other.
Upvotes: 2