CodeBlanks Logo Icon CodeBlanks

Summary - Zustand

Combine create, action and persist to write a persistent counter.

Summary - Zustand

In this group you learned Zustand, create, reading state, actions and persist. create creates the store; you call the returned hook in the component. A selector triggers render only when the relevant field changes. An action updates state with set. persist makes state persistent.

Now we will combine them into a persistent counter. The store definition, reading, increment and persist wrap come together. This pattern is the skeleton of every persistent app with Zustand.

Practice Summary - Persistent counter store

Define the useCounter store. Wrap it with persist. State: count: 0. Action: increment: () => set((s) => ({ count: s.count + 1 })). Persist name: 'counter-storage'. Export it with export const.

Starter code

App.js
import { create } from 'zustand';

// define useCounter with persist

Sample solution

App.js
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export const useCounter = create(persist((set) => ({
  count: 0,
  increment: () => set((s) => ({ count: s.count + 1 })),
}), { name: 'counter-storage' }));

Practice Summary - Counter component

Complete the Counter component. Read the value with const count = useCounter((s) => s.count). Get the action with const increment = useCounter((s) => s.increment). Return <Text>{count}</Text> and an increment button.

Starter code

App.js
import React from 'react';
import { Button, Text, View } from 'react-native';

export function Counter() {
  // get count and increment via selectors; return Text and Button

  return null;
}

Sample solution

App.js
import React from 'react';
import { Button, Text, View } from 'react-native';
import { useCounter } from './useCounter';

export function Counter() {
  const count = useCounter((s) => s.count);
  const increment = useCounter((s) => s.increment);

  return (
    <View>
      <Text>{count}</Text>
      <Button title="Increase" onPress={() => increment()} />
    </View>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the flow parts

Term Meaning
create Creates the store
set Updates state
(s) => s.count Selector
persist Makes persistent

2 Write the persist name value

Question
persist((set) => ({ count: 0 }), { name: '____' })
Answer
persist((set) => ({ count: 0 }), { name: 'counter-storage' })

Explanation: counter-storage is the key name.

All lessons in Advanced