ReactJS Redux

react

Redux is a popular library for managing state in a React application. It is often used in combination with React to provide a central location for storing and managing application state.

One of the key principles of Redux is that the entire application state is stored in a single, immutable object. This means that the state can’t be modified directly, but instead, changes to the state must be made by dispatching actions. An action is a simple object that describes a change to the application state, and it is the only way to update the state.

To use Redux in a React application, you will need to install it first:

npm install redux

Then, you can create a Redux store to hold your application’s state and specify the reducer function that will be used to update the state. The reducer is a pure function that takes the current state and an action as arguments and returns the new state.

Here is an example of a simple Redux store and reducer:

import {createStore} from 'redux';

const initialState = {
    count: 0
};

function reducer(state = initialState, action) {
    switch (action.type) {
        case 'INCREMENT':
            return {count: state.count + 1};
        case 'DECREMENT':
            return {count: state.count - 1};
        default:
            return state;
    }
}

const store = createStore(reducer);

To dispatch an action, you can call the dispatch method on the store:

store.dispatch({type: 'INCREMENT'});

To connect a React component to the Redux store, you can use the connect function from the react-redux library. This function allows you to specify which parts of the state you want to be passed to the component as props, and which actions you want to be able to dispatch from the component.

Here is an example of a simple React component that is connected to the Redux store:

import {connect} from 'react-redux';

class Counter extends React.Component {
    handleIncrement = () => {
        this.props.dispatch({type: 'INCREMENT'});
    }

    handleDecrement = () => {
        this.props.dispatch({type: 'DECREMENT'});
    }

    render() {
        return (
            <div>
                <button onClick={this.handleDecrement}>-</button>
                {this.props.count}
                <button onClick={this.handleIncrement}>+</button>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {count: state.count};
}

export default connect(mapStateToProps)(Counter);

In this example, the Counter component is connected to the Redux store using the connect function. The mapStateToProps function specifies that the count value from the store should be passed to the component as a prop. The component also has two event handlers that dispatch actions to the store when the buttons are clicked.