CodeBlanks Logo Icon CodeBlanks

Action

Learn to define Zustand actions.

Action

In Zustand an action is a function inside the store. To update state you call set. Example: increment: () => set((s) => ({ count: s.count + 1 })). This function is called directly from components; no middle layer like dispatch is needed.

Actions are listed in the store definition; each represents a state change. You can create functions like addItem, removeItem, clear. An action can take any parameter you want; like addItem: (item) => set((s) => ({ items: [...s.items, item] })).

Calling an action

To call an action in a component you first get it from the store hook. You can select only the function with const increment = useCounter((s) => s.increment). Or get the whole store and destructure with const { increment } = useCounter(). Then call increment() on the button's onPress.

Selecting via a selector does not trigger a render as long as the action reference does not change. Zustand keeps action references stable; so selecting via a selector is safe. Each button press runs increment(), updates state and re-renders components reading count.

Practice An increment button

Complete the CounterButton component. Import useCounter from ./useCounter. Get the action with const increment = useCounter((s) => s.increment). Call increment() on the button's onPress.

Starter code

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

export function CounterButton() {
  // get increment via selector and call on press

  return null;
}

Sample solution

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

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

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

Questions and answers

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

1 Write the action body

Question
increment: () => ____((s) => ({ count: s.count + 1 })),
Answer
increment: () => set((s) => ({ count: s.count + 1 })),

Explanation: Write set; it is Zustand's state update function.

2 Why does an action not need dispatch?

  • Because it is a function in the store, called directly
  • Because actions do nothing
  • Because Zustand does not use hooks
  • Because state never changes Correct answer

Explanation: In Zustand an action is called directly.

3 Match the action parts

Term Meaning
increment Action name
set Updates state
(s) => s.increment Selector
onPress Call moment

All lessons in Advanced