Middle
How is state stored in React? What state managers have you used?
sobes.tech AI
Answer from AI
In React, state is stored inside components. Functional components use the useState hook, which allows creating local state. There is also useReducer for more complex state management logic.
For global state, state managers are often used:
- Redux — a classic and popular manager with a centralized store and predictable updates via actions and reducers.
- MobX — a reactive manager using observable objects and automatic component updates.
- Context API — a built-in React mechanism for passing state through the component tree without props.
- Recoil — a modern manager from Facebook with atomic state and convenient dependency management.
Example of local state with useState:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
The choice of manager depends on the scale of the application and architectural requirements.