State Management with Redux
Introduction to Redux
Redux is a state management library that helps you manage global state by providing a single source of truth for your application's state.
// Example Redux store import { createStore } from 'redux'; const initialState = { count: 0, todos: [] }; const reducer = (state = initialState, action) => { switch (action.type) { case 'INCREMENT': return { ...state, count: state.count + 1 }; case 'DECREMENT': return { ...state, count: state.count - 1 }; case 'ADD_TODO': return { ...state, todos: [...state.todos, action.payload] }; default: return state; } }; const store = createStore(reducer);
Try it yourself:
Redux State:
Count: 0, Todos: []
Connecting Redux to React
To use Redux with React, you need to connect your React components to the Redux store.
// Example React component connected to Redux import React from 'react'; import { connect } from 'react-redux'; const Counter = ({ count, increment, decrement }) => (); const mapStateToProps = state => ({ count: state.count }); const mapDispatchToProps = dispatch => ({ increment: () => dispatch({ type: 'INCREMENT' }), decrement: () => dispatch({ type: 'DECREMENT' }), }); export default connect(mapStateToProps, mapDispatchToProps)(Counter);Count: {count}