Redux

Redux is an open-source JavaScript library that is used for managing the application state in a predictable and centralized way. It is commonly used with React, but can also be used with other frameworks or libraries.

The main concept behind Redux is to keep the state of the application in a single state tree, which cannot be modified directly; instead, any changes to the state have to be done through dispatching actions.

Here’s a simple example of how Redux can be used to manage a counter in a React component:

import { createStore } from 'redux';

// Define the reducer function
function counterReducer(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}

// Create a Redux store
const store = createStore(counterReducer);

// Dispatch actions to update the state
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });

// Get the current state from the store
const currentState = store.getState();

// Render the current state in a React component
function Counter() {
  const [count, setCount] = useState(currentState);

  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      setCount(store.getState());
    });

    return unsubscribe;
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => store.dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => store.dispatch({ type: 'DECREMENT' })}>-</button>
    </div>
  );
}

In this example, the counterReducer function takes the current state and an action, and returns the new state based on the type of the action.

The createStore function is used to create a Redux store, which is used to store and manage the state of the application.

The store.dispatch function is used to dispatch actions to the store, which triggers the reducer function to update the state.

The store.getState function is used to get the current state from the store.

Finally, the Counter component uses the useState and useEffect hooks to render the current state from the store, and the store.subscribe function to listen for changes to the state and update the component when necessary.

Leave a Comment

Skip to content