Page Content

Tutorials

What Are The Redux in React.js With Code Example

Redux in React.js

A popular and commonly used data store for JavaScript and React.js apps is Redux. Based on the fundamental idea that all data should be maintained and that data binding should only occur in one direction, it functions. Redux’s design concept’s simplicity and very tiny implementation footprint helped it become popular. Redux is a well-liked data store for projects using React and JavaScript. It adheres to the fundamental idea that information should be preserved and should only move in one direction. The simplicity of the design concept and the comparatively simple implementation helped Redux become popular.

React only describes how to render the screen and manage user interactions, but Redux in React.js centralises application state. This is especially important as a program evolves and its components must communicate data across various channels and tightly nested structures.Only component level state management is supported by React. Many components are used in a large and sophisticated program.

Redux in React.js
Redux in React.js

React suggests utilising attributes to pass the state to the nested component after moving it to the top level component. It is somewhat helpful, but as the number of components rises, it becomes more complicated. At the application level, Redux in React.js chips in and aids in state maintenance. Any component can access the state at any moment with Redux in React.js. Additionally, it permits any component to alter

Core Concepts of Redux

A unidirectional data flow is ensured by Redux’s operation, which is founded on many fundamental ideas:

Store: The whole state of the application is stored in a single JavaScript object called the store. All data that must be shared between components or maintained across various views is centrally stored there. Redux in React.js promotes the usage of “slices” or logical partitioning within the store to keep it manageable as it expands.

Actions: These are straightforward JavaScript objects that explain the event or the desired data alteration. To specify the type of action being carried out, an action must have a type field. It can also include any additional data often referred to as payload that is pertinent to that modification. From components, actions are transmitted to the storage.

Action Creators: A function that returns an action object is an action maker. They standardise action creation and increase code clarity. Action creators are helper methods or functions that produce and return “actions” in React.js applications, especially in Flux or Redux designs. Actions are ordinary JavaScript objects with a type field denoting the change and a payload containing any relevant data.

Dispatcher: This is the application’s main core. Actions are sent to the reducers after being received by it. Redux in React.js sends store operations to relevant reducers; you never call them directly.

Reducers: A pure reducer returns a new state from the current state and an action. The most important criterion for reducers is that they can’t directly change the original state. The new state object should be returned after they have made a copy of the state and applied the modifications to it. Reducers usually decide how to update the state using a switch statement depending on the action.type.

The workflow of a typical Redux store is as follows:

  • A React component obtains the most recent state during application initialisation by subscribing to the store.
  • When a user clicks a button or interacts with a React view, an action is sent out.
  • The dispatcher informs the relevant reducers.
  • The reducer generates and returns a new state from the action and current state. The store adjusts itself.
  • The store re-renders the changed state to all subscribing components.

Debugging and comprehending how data changes in the program are made easy by this unidirectional data flow.

Setting Up Redux in a React Application

Install the framework-agnostic redux package and react-redux, which has Redux store bindings, in React projects.

Installation: To offer the store to your Redux in React.js application, wrap a react-redux Provider component around the root component. Redux will be installed and connected to your root component. Create a base store and display the data in your component. This step will provide you a functional Redux in React.js instance with component information.

Providing the Store to the Application: This gives all component tree child components access to the Redux store without sending it down as props. Your configured Redux store is supplied to the Provider component via store prop.

Creating the Redux Store: Redux’s createStore function creates the store. A reducer or collection of reducers is one of its key arguments. You frequently use combineReducers (also from redux) to merge various reducers into a single root reducer for intricate applications with numerous pieces of state. A particular portion of your application’s state is managed by each reducer.

Code Example:

An abridged version of the “bird watching test application” from will be used to demonstrate Redux features.

import React, { useReducer, useState } from "react";
// Action types
const ADD_BIRD = "ADD_BIRD";
const INCREMENT_BIRD = "INCREMENT_BIRD";
// Reducer
function birdsReducer(state, action) {
  switch (action.type) {
    case ADD_BIRD:
      return [...state, { name: action.name, views: 1 }];
    case INCREMENT_BIRD:
      return state.map(b =>
        b.name === action.name ? { ...b, views: b.views + 1 } : b
      );
    default:
      return state;
  }
}
export default function App() {
  const [birds, dispatch] = useReducer(birdsReducer, [{ name: "robin", views: 1 }]);
  const [birdName, setBirdName] = useState("");
  return (
    <div style={{ padding: "20px" }}>
      <h1>Bird Watcher</h1>
      {/* Add Bird Form */}
      <input
        value={birdName}
        onChange={(e) => setBirdName(e.target.value)}
        placeholder="Bird name"
      />
      <button
        onClick={() => {
          if (birdName.trim()) {
            dispatch({ type: ADD_BIRD, name: birdName.trim() });
            setBirdName("");
          }
        }}
      >
        Add Bird
      </button>
      {/* Bird List */}
      <ul>
        {birds.map((bird) => (
          <li key={bird.name}>
            {bird.name} – Views: {bird.views}{" "}
            <button onClick={() => dispatch({ type: INCREMENT_BIRD, name: bird.name })}>
              +
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Output:

Bird Watcher

Bird name     Add Bird

• robin – Views: 1 +

Explanation of the Code Example

Your code is a small, self-contained React.js web application that uses a common state management style. This version uses React’s useReducer hook instead of Redux in React.js massive external library. This hook centralises complex state logic in a reducer function, making it powerful.

The application consists of three main parts:

The Reducer Function (birdsReducer): Central to the app is this reasoning. The current state and action are input to this pure function. The action describes what happened (a bird was added or a view was increased). Following that operation, the reducer returns a new state. Immutability requires that the reducer always delivers a fresh state object, never modifies it.

The Main Application Component (App): The Main Application Component (App) initialises state and accesses dispatch via the useReducer hook. Call dispatch to send an action to the reducer. The App component gives BirdList and BirdForm the current state (birds) and dispatch function as props.

Child Components (BirdList and BirdForm): These child components (BirdList and BirdForm) handle the user interface. BirdList displays birds and view counts and sends an INCREMENT BIRD action when clicked. BirdForm submits an ADD BIRD action when a new bird is entered.

Benefits and Limitations of Redux

Centralized state management: Offers an application-wide data store that is one and the same. State management libraries go beyond Redux. Zustand is another library. Redux Dev Tools assist us debug our Redux in React.js applications like Redux in React.js Dev Tools.

Predictable state changes: Predictable state changes in React ensure that the application’s state updates consistently and clearly, making it more stable and manageable. Most of React’s unidirectional data flow comes from props, which ensures that components get data in a predictable fashion and don’t directly change variables.

Improved debugging: Redux DevTools highlight actions, state changes, and effects, simplifying debugging. The Chrome and Firefox React Developer Tools browser plugin improves Redux in React.js debugging. This powerful tool lets developers see each component’s props, state, and context in real time, removing the need for console.log statements or debuggers.

Scalability: Complex applications that maintain state across routes or components benefit from scalability. React’s scalability is its capacity to support huge, intricate, and rapidly expanding applications while preserving management and performance.

Maintainability: Code that is easier to manage and comprehend is maintained by decoupling logic from user interface elements.

Testability:The testability of reducers is simple because they are pure functions. The fundamental architectural ideas of React and the extensive collection of testing tools make it far more testable. Fundamentally, React promotes the creation of user interfaces as a group of discrete, autonomous, self-contained components.

Limitations and Considerations

Boilerplate code: Redux Toolkit, an officially supported project, reduces boilerplate code for reducers and actions, however in smaller configurations, Redux in React.js might introduce a lot.

Learning curve: Compared to more straightforward state management techniques, initial understanding of the concepts of actions, reducers, and the store might be difficult for novices.

Not always necessary: UseState and useReducer hooks with the Context API may work for smaller projects or apps with isolated components. React apps need not use Redux.

Conclusion

React.js useReducer, like Redux in React.js actions, reducer, shows unidirectional state management in the Bird Watcher example. Having one reducer for all bird data makes updates predictable and easy to track. Actions provide changes, and the reducer applies them without changing the state.

This reduced method is best for smaller applications or feature-specific state, while complete Redux in React.js with react-redux is better for large, complicated applications with shared information across multiple components. The example shows that explicit data flow, clean update functions, and centralised state may produce scalable and maintainable React apps without Redux.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index