I like this post by Dan Abramov, the author of Redux, on how you might not need Redux:
If you’re working on an extensible terminal, a JavaScript debugger, or some kinds of webapps, it might be worth giving Redux a try, or at least considering some of its ideas.
However, if you’re just learning React, don’t make Redux your first choice. Instead learn to think in React. Come back to Redux if you find a real need for it, or if you want to try something new. But approach it with caution, just like you do with any highly opinionated tool.
In the article he also included an example which uses the Redux way of thinking (actions being dispatched, and reducers adjusting the state), but does not have Redux installed:
import React, { Component } from 'react';
const counter = (state = { value: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { value: state.value + 1 };
case 'DECREMENT':
return { value: state.value - 1 };
default:
return state;
}
}
class Counter extends Component {
state = counter(undefined, {});
dispatch(action) {
this.setState(prevState => counter(prevState, action));
}
increment = () => {
this.dispatch({ type: 'INCREMENT' });
};
decrement = () => {
this.dispatch({ type: 'DECREMENT' });
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
Redux library itself is only a set of helpers to “mount” reducers to a single global store object. You can use as little, or as much of Redux, as you like.
Related: A cartoon intro to Redux →
Leave a comment