Press "Enter" to skip to content

What is Redux in React JS?

0

Redux is a state management library that is often used with React Js. It provides a centralized store for the application state and allows for easy management of the state through actions and reducers. In this tutorial, you will understand the working of Redux state management.

Here is a simple example of how you might use Redux in a React application:

First, you would set up your store and create the initial state:

import { createStore } from 'redux';

const initialState = {
  count: 0,
};

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

Then, you would create your actions:

const increment = () => ({
  type: 'INCREMENT',
});

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

Finally, you would connect your React component to the Redux store:

import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';

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

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(decrement())}>-</button>
    </div>
  );
}

export default App;

In this example, when the user clicks the “+” or “-” button, an action is dispatched which updates the state in the store. The component then re-renders with the updated state.

Hope You guys understand this example of Redux.

Configuration setting for .conf file in apache
How to connect Flask application to MySQL? - Python Web Development