Course contentsShow
← React
Lesson 1764 of 2,39641. State Management EcosystemFree lesson

Actions and Computed Values

Organizing state mutations into functions and using `derive()` or getters for computed/derived state.

Actions and Computed Values

You'll learn how to organize state changes into reusable functions and derive computed state without manual syncing in Valtio.

Organizing Mutations with Actions

Even though Valtio lets you mutate state directly, scattering mutations throughout your components creates chaos. Instead, organize mutations into action functions that encapsulate the "what" and "why" of state changes.

Think of actions like TV remote buttons—each one does a specific, named thing (Volume Up, Channel Change) rather than letting everyone directly fiddle with the TV's internals.

import { proxy } from 'valtio';

const store = proxy({
  count: 0,
  todos: []
});

// Actions: named functions that describe intent
export const actions = {
  increment() {
    store.count++;
  },
  
  addTodo(text) {
    store.todos.push({ 
      id: Date.now(), 
      text, 
      done: false 
    });
  },
  
  toggleTodo(id) {
    const todo = store.todos.find(t => t.id === id);
    if (todo) todo.done = !todo.done;
  }
};

Now your components call actions.increment() instead of store.count++ directly—clearer intent, easier testing, better maintainability.

Computed Values with derive()

For derived state (values calculated from other state), Valtio offers derive() from valtio/utils. This creates getters that automatically recompute when dependencies change—no manual syncing required.

import { derive } from 'valtio/utils';

const derived = derive({
  completedCount: (get) => 
    get(store).todos.filter(t => t.done).length,
    
  summary: (get) => {
    const s = get(store);
    return `${s.count} clicks, ${get(derived).completedCount} done`;
  }
});

Access derived values just like regular state: derived.completedCount. Valtio tracks dependencies automatically.

Key Takeaway: Actions centralize state mutations for clarity and maintainability, while derive() creates reactive computed values that update automatically when their dependencies change—keeping your state logic organized and your components clean.