Chapter 11. State Management in Larger Applications
In Chapter 10, we used the flashcard application as a jumping-off point to discuss the structure of larger applications. One of the common issues that React applications encounter as they grow is state management. React Native is no different: as our application gets larger, we can benefit from using a state management library. In this chapter, we’ll look at Redux, a library for managing data flow, and integrate it with our flashcards application. We’ll also integrate AsyncStorage with our Redux store.
Using Redux to Manage State
Redux is based somewhat on the Flux data flow pattern, as well as functional programming concepts. Previous examples we’ve looked at in this book haven’t required much in the way of data flow management. With smaller applications, communicating between components is usually a trivial issue. Consider the case where a button tap has an impact on the parent’s state:
class
Child
extends
Component
{
render
()
{
<
TouchableOpacity
onPress
=
{
this
.
props
.
onPress
}
>
<
Text
>
Child
Component
<
/Text>
<
/TouchableOpacity>
}
}
By passing a callback from the parent to the child, we can alert the parent about interactions with the child:
class
Parent
extends
Component
{
constructor
(
props
)
{
super
(
props
);
this
.
initialState
=
{
numTaps
:
0
};
}
_handlePress
=
()
=>
{
this
.
setState
({
numTaps
:
this
.
state
.
numTaps
+
1
});
}
render
()
{
<
Child
onPress
=
{
this
.
_handlePress
}
/>
}
}
For simple use cases, this pattern works just fine.
Our need ...
Get Learning React Native, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.