What is Redux? give an example

What is Redux? give an example

Redux is a predictable state container for JavaScript applications, often used with frameworks such as React to build user interfaces. It assists in managing the state of an application in a predictable manner, simplifying comprehension and debugging.

In Redux, the application state is stored in a single, immutable object called the "store." Actions are dispatched to describe changes to the state, and reducers are functions that specify how the state should change in response to these actions. The state changes are predictable and adhere to a unidirectional data flow.

Here's a simple example of a Redux setup with React:

  1. Install the required packages:
npm install redux react-redux
  1. Create a Redux store and define actions and reducers:
// actions.js
export const increment = () => ({
  type: 'INCREMENT',
});

export const decrement = () => ({
  type: 'DECREMENT',
});

// reducers.js
const initialState = {
  counter: 0,
};

const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, counter: state.counter + 1 };
    case 'DECREMENT':
      return { ...state, counter: state.counter - 1 };
    default:
      return state;
  }
};

export default counterReducer;
  1. Create the Redux store and integrate it with React.
// store.js
import { createStore } from 'redux';
import counterReducer from './reducers';

const store = createStore(counterReducer);

export default store;
  1. Use the store in a React component:
// App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actions';

const App = () => {
  const counter = useSelector((state) => state.counter);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Counter: {counter}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
    </div>
  );
};

export default App;

In this example, the Redux store holds the state, and the increment and decrement actions describe the state changes. The counterReducer specifies how the state should be updated based on these actions. The React component (App.js) uses the useSelector and useDispatch hooks from react-redux to connect to the Redux store and dispatch actions.