useReducer

    We can use React's useReducer hook to manage our application data. In this example we'll look at a small To-Do list app that manages its data with useReducer.

    Reducer patterns

    While useReducer doesn't enforce any particular types/shapes for states and actions, there are a few that are common when managing medium/large quantities of data:

    • The actions we pass to the reducer are objects containing a type and payload
    • We often define constants for the type, enumerating every action our reducer function knows how to handle
    • We expose actionCreator functions that abstract the details of our action objects from the rest of the app
    • Our state is an object, so that we can add fields to it easily as our app grows

    These patterns help keep the reducer code self-contained for each kind of entity in our app (e.g todos, posts, photos).

    Example

    Using the terminology from the Project Structure section, this app contains:

    • A "container" component, App, that connects our application/business logic for adding and removing To-Do items with our UI components
    • 3 "presentational" components that we use to display our UI: List, Input, and Title
    • A todos file that contains the initial state of our app and a reducer function for updating the state

    Want to learn React Native in-depth?

    If you like React Native Express, you'll love my new book, Fullstack React Native: The complete guide to React Native! Throughout the book, we'll build 7 full apps, covering complex topics like navigation, gestures, and native modules. We don't assume any knowledge of React or newer JavaScript language features, so you can dive right in regardless of your experience level. The book comes in PDF, EPUB and MOBI formats.