Pages

How React hooks Completely replace redux?

Since the introduction of the React hooks API, many questions have been raised about whether or not React hooks will replace Redux.


The overlap between hooks and redux is minimal.


Without utilizing class components, you may leverage React capabilities like state and lifecycle functions with React hooks. Any JavaScript application can use Redux, a state management library that is independent of JavaScript. Depending on the requirements of the application, Redux and React hooks can be used independently or in combination. Each has benefits and drawbacks of their own.





Hooks did not grant us magical new state capabilities. Instead, it improved the API for functions that React already allowed us to perform. However, the hooks API has greatly improved the usability of the native React state API, and because it is simpler than the class model it replaces, I utilise component state far more frequently now than I previously did when it makes sense.


We need a clearer understanding of why we might consider Redux in the first place before we can comprehend what I mean by that.


What is Redux?


Redux is a dependable state management framework and library that interacts well with React.


Redux's main selling factors include:


  • Resolution of deterministic states (enabling deterministic view renders when combined with pure components).

  • state of a transaction.

  • Separate state management from side effects and I/O.

  • only reliable source for application state information.

  • State can be easily shared across several components.

  • Transaction monitoring (auto-logging action objects).

  • repairing time travel bugs.


Redux, in other terms, endows you with superhuman debugging and code organisation abilities. It makes it simpler to create better maintainable code and much simpler to find the primary source of a problem.


What are React Hooks?


React Hooks are unique functions that let React components connect to particular React functionalities. They provide state and other React capabilities without the need for class creation. In React 16.8, hooks are a brand-new feature. You can remove stateful logic from a component using hooks so that it can be tested separately and used again. Additionally, hooks offer a more direct API to React concepts like props, state, context, refs, and lifecycle events that you are already familiar with.


React hooks' main selling points are:


  • Without requiring a class, use state to hook into the component lifecycle.

  • Instead of dividing the functionality amongst different lifecycle methods, group relevant logic together in one location in your component.

  • Share reusable actions without regard to how a component is implemented (like the render prop pattern).


Note that these wonderful advantages don't actually overlap with Redux's advantages. The deterministic state model of Redux is easy to combine with the hooks of React, which can and should be used to get deterministic state updates. This is how React makes deterministic view rendering possible and is one of the main inspirations behind the development of React.


There is no need to select one over the other with tools like the useReducer hook in React and the react-redux hooks API. Apply both. blend and match


When to Use Hooks


Redux is not necessarily necessary for every project or component. I can't think of a decent reason to add Redux's complexity if your app only has one view, doesn't save or load state, and doesn't use asynchronous I/O.


Additionally, if your component


  • Utilises no network.

  • Does not load or save state.

  • Doesn't share state with other components that aren't children.

  • Does require a transient local component state.

The component state concept that comes with React may be useful in your application. In certain circumstances, React hooks will be quite useful. The local component state useState hook from React, for instance, is used in the following form.



import React, { useState } from 'react';

import t from 'prop-types';

import TextField, { Input } from '@material/react-text-field';

const noop = () => {};

const Holder = ({

  itemPrice = 175,

  name = '',

  email = '',

  id = '',

  removeHolder = noop,

  showRemoveButton = false,

}) => {

  const [nameInput, setName] = useState(name);

  const [emailInput, setEmail] = useState(email);

const setter = set => e => {

    const { target } = e;

    const { value } = target;

    set(value);

  };

return (

    <div className="row">

      <div className="holder">

        <div className="holder-name">

          <TextField label="Name">

            <Input value={nameInput} onChange={setter(setName)} required />

          </TextField>

        </div>

        <div className="holder-email">

          <TextField label="Email">

            <Input

              value={emailInput}

              onChange={setter(setEmail)}

              type="email"

              required

            />

          </TextField>

        </div>

        {showRemoveButton && (

          <button

            className="remove-holder"

            aria-label="Remove membership"

            onClick={e => {

              e.preventDefault();

              removeHolder(id);

            }}

          >

            &times;

          </button>

        )}

      </div>

      <div className="line-item-price">${itemPrice}</div>

      <style jsx>{cssHere}</style>

    </div>

  );

};

Holder.propTypes = {

  name: t.string,

  email: t.string,

  itemPrice: t.number,

  id: t.string,

  removeHolder: t.func,

  showRemoveButton: t.bool,

};

export default Holder;

This code uses useState to keep track of the ephemeral form input states for name and email:


const [nameInput, setName] = useState(name);

const [emailInput, setEmail] = useState(email);



You may have noticed that a Redux removeHolder action creator is also putting in props. Combining styles is acceptable.


The local component state has always been OK for situations like this, but before React hooks, I might have been tempted to put it in Redux and get the state from props.


The component state would have required the use of a class component, initial state setting using the class instance property syntax (or a function Object() { [native code] } function), and other additional complexity that was unnecessary in order to avoid Redux. Redux has plug-and-play solutions for managing form state, which made it easier for me to make sure that changing form state didn't affect my business logic.


The decision was easy because I already used Redux in all of my non-trivial apps: Redux (nearly) everything!


The decision is still straightforward as of right now:


Component state for the component state, redux for the application state


When to Use Redux


Another frequent query is, "Should you store everything in Redux?" Will it not compromise time travel debugging if you do not?"


No, because applications have a lot of state that is too granular and transient to offer valuable data for tasks like logging telemetry or time travel debugging. You probably don't need to save every user input and mouse movement in Redux state unless you're developing a real-time collaborative editor. Redux state grows by adding items, which adds another layer of abstraction and the complexity that comes with it.


To put it another way, you should feel free to use Redux, but you should have a good justification for doing so.


In the event that your component:


  • Similar to network or device APIs, uses I/O.

  • State is loaded or saved.

  • State is shared by components that are not children.

  • Handles any shared business logic or data processing with other application components.


Another example from the TDDDay app is like follows:


import React from 'react';

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

import { compose } from 'ramda';

import page from '../../hocs/page.js';

import purchase from './purchase-component.js';

import { addHolder, removeHolder, getHolders } from './purchase-reducer.js';

const PurchasePage = () => {

  // You can use these instead of

  // mapStateToProps and mapDispatchToProps

  const dispatch = useDispatch();

  const holders = useSelector(getHolders);

const props = {

    // Use function composition to compose action creators

    // with dispatch. See "Composing Software" for details.

    addHolder: compose(

      dispatch,

      addHolder

    ),

    removeHolder: compose(

      dispatch,

      removeHolder

    ),

    holders,

  };

return <Purchase {...props} />;

};

// `page` is a Higher Order Component composed of many

// other higher order components using function composition.

export default page(PurchasePage);



None of the DOM is handled by this component. It is a container component that assigns import presentation component with DOM concerns. Utilizing the React-Redux hooks API, it connects to Redux.


It makes use of Redux since, after the purchase flow is complete, we'll need to save the data to a database. Other elements of the UI depend on the data this form cares about.


It doesn't only care about one part's state; instead, it cares about the state of many parts at once. This state isn't temporary; it lasts through multiple page views or sessions. Local component state won't help with any of these problems unless you build your own state container library on top of the React API, which is much harder than just using Redux.


React's suspense API could one day assist in saving and loading state. To find out if the suspense API can take the place of my Redux saving/loading routines, we'll have to wait until it launches. Without having to simulate I/O services, Redux enables us to neatly isolate side-effects from the rest of the component code. (I favour redux-saga over thunks since it allows for the isolation of effects.) Effect isolation will be a need for React's APIs in order to compete with Redux in this use case.


Final thoughts:

React Hooks are a great addition to the React library, and they give developers powerful tools for making stateful components. React Hooks don't completely replace Redux, but they do give React applications another way to handle state. Even though React Hooks can be used to manage state, Redux is still the best way to manage and store state across an entire application.


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...