preface

React Hooks have received a lot of hype since they were introduced, and a lot of problems have followed.

Here is a discussion of one of these topics: Will React Hooks replace traditional Redux?

My answer: No.

In my opinion, the Hooks do not provide any new state functionality compared to the traditional Class Component, but are merely enhancements to the original API.

Hoos is much simpler than before, improves the usability of native apis, and can be used in more and more scenarios.

To illustrate my point, let’s do a little review.


What is the story

Redux is a predictable state management tool that can be easily integrated into the React application. It has many advantages, such as:

  • Single data source
  • Data sharing
  • State of affairs
  • Isolate data state I/O from side effects
  • State back, also known asA time machine
  • Powerful debugging capabilities brought by a series of auxiliary tools

In general, Redux provides code organization and debugging capabilities for large applications, helping you quickly locate problems when they go wrong.

What is the Hooks

In this post, you will find that you are interested in understanding the basic functions of the Hooks.

New features: [a comprehensive understanding of the React Suspense and Hooks] [segmentfault.com/a/119000001…].

Hooks main advantages:

  • You can define data state in functional components, and you can also simulate lifecycle methods with Hooks.
  • Logic reuse; Common logic can be abstracted into individual hooks, moving from traditional lifecycle oriented programming to business logic oriented programming.
  • Share public actions, like Render Props.

You know, there are several react-redux Hooks(react-redux.js.org/next/api/ho…) And Reducer Hook (reactjs.org/docs/hooks-…). Such tools, we do not have to tangle between the two how to choose, rain and dew evenly, happy.

Hooks brought those changes

  • Changed the way we write components, and with more options, you canDiscard the life cycle sideLaws, embrace Hooks.
  • Render PropsThe model, too, has a better home

Hooks cannot replace technologies

  • Redux
  • HOC
  • Container componentsandThe view componentsThe separation between pure logic and visual effects is easier to test.

When to Use Hooks

You can use Redux to manage state any time you like. But if your application is simple enough, contains only a single view, needs a place to temporarily store state, doesn’t need to share data with other components, or even doesn’t have asynchronous I/O (which doesn’t matter). This is where Hooks come in, Redux in these situations, of course, but it’s called killing a penis.

Here’s an example:

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>
  );
};

export default Holder;

Copy the code

The example above uses useState to track the name and email in the form:

const [nameInput, setName] = useState(name);
const [emailInput, setEmail] = useState(email);
Copy the code

You might notice that there’s also a removeHolder, this action Creator from Redux. In this mode, all methods can be mixed and matched.

You can use Local State to save and update the state before the Hooks occur to cope with this situation. If I were writing this, I’d be more inclined to plug it into a Redux and get the state through a Prop.

So far, in every React app I’ve made, I’ve used Redux, and the principle is simple:

Use component state for component state and Redux for application state. Each brings out the best in the other.

When to use Redux

Another common question is, should I put all the data and states in Redux? If we don’t do that, is there no way to use time travel?

The answer is no.

Because many states in an application are temporary, limitations do not provide enough information for log telemetry or time travel. Unless you’re working on a collaborative text editor (Lark Docs, Tencent Docs, etc.), you can save every user action, every changeSet data, including cursor position and so on.

Every time you add data to a Redux, it adds a layer of abstraction and extra complexity.

In other words, every time you use a Redux, know why you need it. Consider using Redux if your application has the following requirements:

  • The state needs to be saved or loaded
  • Sharing state across components
  • You need to share business logic or data processing with other components

Here’s another example:

Visit tddday.com/

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 usingfunction composition.
export default page(PurchasePage);

Copy the code

This component does not handle any DOM, it is a purely display component and is connected to Redux using the React-Redux hooks API.

Redux is used because other parts of the form require the data. Its state is not localized to a single component, but is shared between components;

Redux allows us to cleanly separate side effects from other component logic without requiring us to simulate I/O services.

The reason I prefer redux-Saga to Redux-Thunk is because of the latter’s isolation feature).

To catch up with Redux on this use case, the React API needs to provide side effect isolation.

Redux is an architecture

Redux is very different from a state management library. But it is essentially a subset of the Flux architecture.

Redux has always been closer to an architecture and a non-mandatory convention than libraries.

In fact, the basic implementation of Redux requires only a few dozen lines of code.

That’s one of the great things about Redux. If you want to use more native component state and hook apis and don’t want to cram everything into Redux, that’s fine.

React provides a useReducer hook that you can use to access your Redux style Reducer. This is useful for unusual state logic, dependent states, and so on.

If your use case is to load temporary state into a single component, you can also use the Redux architecture, but use useReducer Hooks instead of Redux to manage state.

If you want to maintain or share this state later, you need to save it to Redux.

conclusion

Hooks are not a replacement for Redux, they give us more flexibility and possibilities to write components. I hope that feers will embrace these new features and find their favorite development positions

The writing is shallow, if there are omissions, please correct.

Attached link: medium.com/javascript-…