Reputation: 215
I am thinking of creating a list components which receive list of items and then return a list of <li></li>
. Moreover, the list can be appended dynamically via ajax call.
I would like to ask in this situation, where should I store the data, props or state?
Upvotes: 1
Views: 418
Reputation: 634
In most cases: use state for data that changes over time.
A common way of doing this is to have two components, List
and ListItem
. The List
component should handle the state, ajax calls and the transfer of list content as props to the child component ListItem
.
<List>
<ListItem>
<ListItem>
<ListItem>
...
</List>
So List
stores the data as state. And ListItem
is stateless and just receive its data from List
.
React docs: What Components Should Have State?
Most of your components should simply take some data from props and render it. However, sometimes you need to respond to user input, a server request or the passage of time. For this you use state.
Try to keep as many of your components as possible stateless. By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.
A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way.
Maybe this helps to understand the structure of building react apps: Tutorial: Thinking in React
Upvotes: 1