Search⌘ K
AI Features

Using XState for the FavoritedImages Surface

Explore how to build and integrate an XState machine for the FavoritedImages surface in a React Native social media app. Learn to configure React context and state hooks to manage liked images effectively. Understand the connection between XState context and React context, and how to update lists dynamically. This lesson prepares you to handle data flow and synchronization using XState in real-world scenarios.

So far, we have set up a basic machine that could be used to control the user flow in the app. Let’s add a new machine for our real-world use case: liking images in a social media clone app.

Minimum viable product

We’ll start by creating a machine minimum viable product (MVP):

Javascript (babel-node)
// src/machines/likeImagesMachine.js
import { createMachine } from "xstate";
/**
* XState machine for managing liked images.
*/
export const likeImagesMachine = createMachine({
id: "likeImagesMachine",
// Context contains the likedImages array
context: {
likedImages: [
{ /* Example Image Object 1 */ },
{ /* Example Image Object 2 */ },
// ... more image objects
],
},
// Initial state when the machine is created
initial: "loading",
// States of the machine
states: {
loading: {}, // State for loading initial data
ready: {}, // State when the machine is ready
error: {}, // State for handling errors
},
});

Let’s analyze this code from the top:

  • Line 3: We start by importing the createMachine function, which we use on the very first line of the likeImagesMachine function on line 9.

  • Lines 13–18: We set the ID of the machine and the context of the machine. Bear in mind that XState context is different from React context. We’ve talked a lot about ReactJS context; we know it can be used to share state between components. ...