Middle
What libraries have you used for state management in React?
sobes.tech AI
Answer from AI
For state management in React, the following libraries are often used:
- Redux — a classic library with a centralized store and Flux pattern. It allows predictable state management, especially in large applications.
- MobX — a simpler and reactive approach to state management with automatic change tracking.
- Recoil — a library from Facebook providing atomic state and convenient selectors.
- Context API — a built-in React mechanism for passing state through the component tree without props, suitable for simple cases.
Example of using Redux:
import { createStore } from 'redux';
const reducer = (state = { count: 0 }, action) => {
switch(action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
};
const store = createStore(reducer);
store.dispatch({ type: 'INCREMENT' });
console.log(store.getState()); // { count: 1 }