As React apps grow, managing shared and app-wide state can become challenging. Dedicated state management libraries help tackle these complexities.

Let’s compare popular options:

Redux

Redux uses a centralized store for state:

1
2
3
4
5
6
7
8
// Store with root reducer
const store = createStore(rootReducer);

// Dispatch actions  
store.dispatch(addTodo(text));

// Selectors
const todos = useSelector(state => state.todos);

Redux enforces unidirectional data flow inspired by functional programming.

MobX

MobX uses observable variables that update reactively:

1
2
3
4
5
6
7
8
9
// Observable store
const store = observable({
  todos: []
});

// Computed values derived from store 
const completedTodos = computed(() => {
  return store.todos.filter(todo => todo.complete);
});

MobX automatically tracks dependencies and re-renders on changes.

Recoil

Recoil introduces shared state atoms:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Atom
const textState = atom({
  key: 'textState',
  default: '',
});

// Component
function TextInput() {
  const [text, setText] = useRecoilState(textState);
  
  // ...
}

Atoms provide a minimal interface for shared state.

Summary

  • Redux - Centralized immutable stores
  • MobX - Reactive observable variables
  • Recoil - Shared state atoms

Each library brings unique tradeoffs. Consider app needs to choose the right state tool.