Trivia Questions1 min readPremium

MVVM in Frontend Applications

Model-View-ViewModel (MVVM) is an architecture pattern that separates what the UI looks like from the logic that drives it. In React and React Native codebases it maps naturally onto components and custom hooks. The pattern originated at Microsoft; see Model-View-ViewModel for its history.

1. The three layers

Layer Owns Must not
Model Domain data, validation, and I/O through services/repositories (API, storage) Know about UI
ViewModel UI state, derived values, and commands the view can call Render markup or touch the DOM
View Layout and presentation, binding to the ViewModel Fetch data or contain business rules

2. ViewModel as a custom hook

// todos.service.ts (Model / service layer)
export const todosService = {
  list: () => api.get('/todos'),
  toggle: (id) => api.post(`/todos/${id}/toggle`),
};

// use-todos-view-model.ts (ViewModel)
export function useTodosViewModel() {
  const [todos, setTodos] = useState([]);
  const [filter, setFilter] = useState('all');

  useEffect(() => { todosService.list().then(setTodos); }, []);

  const visible = useMemo(
    () => todos.filter(t => filter === 'all' || (filter === 'done') === t.done),
    [todos, filter],
  );

  const toggle = useCallback(async (id) => {
    setTodos(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));
    await todosService.toggle(id);
  }, []);

  return { visible, filter, setFilter, toggle };
}

// TodosView.tsx (View)
export function TodosView() {
  const vm = useTodosViewModel();
  return <TodoList items={vm.visible} onToggle={vm.toggle} />;
}

3. Why teams adopt it

  • Testability: the ViewModel can be tested with a hook test renderer and a mocked service, without rendering UI.
  • Reuse: the same ViewModel can drive a web view and a React Native view, or a mobile and a desktop layout.
  • Readable views: components become mostly declarative markup.
  • Swappable I/O: replacing REST with GraphQL only touches the service layer.

4. Common mistakes

  • Fat views: fetch calls and business rules inside JSX components.
  • God view models: one hook managing an entire screen with dozens of fields. Split by feature.
  • Unstable outputs: returning new functions/objects every render, which defeats React.memo in the view. Memoize commands and derived values.
  • ViewModel calling navigation inside render: side effects belong in effects or commands.

5. MVVM vs MVC

In MVC, a controller receives input and updates the model and view. In MVVM, the view binds to observable state exposed by the ViewModel, and data flows back via commands. React’s re-render-on-state-change is that binding.