Loading...
Loading...
Redux is a library for managing state in JavaScript applications. It helps create applications that behave predictably, are easy to test and work in various environments.
createStore functiontype propertyconst action = {
type: 'ADD_TODO',
payload: 'Learn Redux'
};
const todoReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload];
default:
return state;
}
};
Single source of truth
State is read-only
Changes are made with pure functions
// Action Creator
const addTodo = (text) => ({
type: 'ADD_TODO',
payload: text
});
// Reducer
const todoReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload];
default:
return state;
}
};
// Store
const store = createStore(todoReducer);
// Subscribe to changes
store.subscribe(() => console.log(store.getState()));
// Dispatch action
store.dispatch(addTodo('Learn Redux'));
Redux should be used when:
Important to remember:
Redux adds additional complexity to application. For small projects built-in React state management may be sufficient.