Philosophy and Design Goals
- You shouldn't need a book on functional programming to use Redux.
- Everything (
Storesreducers, Action Creators, config) is hot reloadable.- Efficiently subscribe to finer-grained updates than individual Stores.
- Provides hooks for powerful devtools (e.g. time travel, record/replay)
- Extension points so it's easy to support promises or generate constants outside the core.
useSelector
hooks APIconst mapState = (state) => ({
todos: selectFilteredTodos(state)
})
const mapDispatch = (dispatch) => (
bindActionCreators({ addTodo, toggleTodo }, dispatch)
)
function TodoList({ todos, addTodo, toggleTodo }) {
// render
}
export default connect(mapState, mapDispatch)(TodoList);
function TodoList() {
const todos = useSelector(selectFilteredTodos);
const dispatch = useDispatch();
// render
}
// Split across constants/todos.js, actions/todos.js, reducers/todos.js
export const ADD_TODO = 'ADD_TODO'
export const addTodo = (id, text) => ({
type: ADD_TODO, text, id
})
export default function todosReducer(state = initialState, action) {
switch (action.type) {
case ADD_TODO: {
return state.concat({
id: action.id, text: action.text, completed: false
})
}
}
}
const todosSlice = createSlice({
name: "todos",
initialState: [],
reducers: {
addTodo: (state, action) => {
state.push(action.payload);
},
},
});
export const { addTodo } = todosSlice.actions;
export default todosSlice.reducer;
createStore
useGetPokemonQuery("pikachu")
connect
-> hookscreateSlice
Redux is designed to answer the question: when does a given slice of state change, and where does the data come from? It's not designed to be the most performant, or the most concise way of writing updates. Its focus is on making the code predictable.
state.value = 123
Date
, Map
, Set