(However, this only works on closed systems!)

In the early days, I decided to use useReducer or a set of state management libraries under hooks. After careful consideration in the combination project, I found the advantages of this solution, and perhaps combined use is the best solution

The reasons for the misunderstanding of useReducer are simple:

  1. Type support is very poor (JS/TS does not have good inverter type support, no pattern recognition, as shown by comparing useReducer on ReasonML)
  2. No pattern recognition (ibid.)
  3. Unable to use third-party hooks ecosystem inside useReducer

A simple example is const {data,error} = useSwr(key,fetcher). This code converts the request process into a data-driven data,error state, and responds to request, delay, screen focus, rotation, and anti-shake functions

Using such third-party apis during development can be much more effective

However, if you use useReducer on this logic, you can no longer use the reducer API called useSwr because the reducer internal code

Redux, Mobx and other useReducer tools are not included in the discussion. Due to the lack of Module function, there is no ability to control initialization (i.e. state management function cannot be initialized with the initialization of components, iteration, asynchronous rendering loses programmability). This has resulted in a lack of use in most scenarios (except for cross-platform and the desire to skip DSL compilation, which is a rare and undesirable requirement, such as RN and flutter schemes, where flutter is superior).

However, in the absence of a professional product manager or business expert, in the absence of design, and in the absence of a fully developed ecosystem for the new version of the superposition (e.g. Antd useForm is not a logical API that ignores graph dependencies, resulting in @testing-library/react-hooks not being used), Tools such as Redux may be more suitable for unstable projects (TDD is still preferred when the ecosystem is perfect, even without top-level design, because the logic itself is abstract, debugging by printing between a layer of DOM and a layer of VM is definitely not a good choice, direct debugging logic is the standard process)

Is useReducer useless in the context of hooks?

As mentioned above, at least the react example does not illustrate the significance of useReducer:

Just because useCallback has changed? You need to use useReducer Dispatch?

const [todos,dispatch] = useReducer(todosReducer)
return <TodosState value={todos}>
  <DeepTreeWithState/>
  <TodosDispatch.Provider value={dispatch}> 
    <DeepTreeWithDispatch />
  </TodosDispatch.Provider>
</TodosState>
Copy the code

Even standard practice should be this ugly?

Control view always depends on useMemo, scheduling logic is also a part of business logic, which can not be avoided.

The implication of returning the unsplit JSX itself is that the view changes with all the state, props, and context, which is logical, while dispatch is counter-intuitive, if not nonintuitive

Should useReducer be used? Now, there are some situations where you should use it, but not in the react document (at least not as easily as he says).

When do YOU need to use useReducer?

Closed systemAccused of entropy

Entropy: A general measure of the state of some system of matter, the degree to which it is likely to occur

It can be roughly understood as the number of possible states of an object at the same time, which includes both the number of states and the possibility of states

Remember that? React although the hooks update has made significant functional improvements, the data-driven principles remain the same

After all, the direct transition from concrete to abstract programming is too big, and the front end is mostly at the view development level, so maybe states are more important than events?

Functional is, however, should not have too much state, no Shared state even stateless, because the function itself is to change the abstract, using state simulation concept programming, make up the top functional design approach of the board, there are a lot of sacrifice (such as a lack of self explanatory programming concept, no covariant type, namely type cannot be top-down, etc.)

The reality, however, is that the front end must have both and must respect state, because the front end development itself is the intermediary, itself the middleware for views and consistent data, and state cannot get around

Also, even Angular, which is known for being event-driven (zone-driven), doesn’t have the same kind of stateless flow as CycleJS, and cycleJS is tepid enough to prove it

The state, then, and the meaning behind it, is intriguing

because

State is entropy

React programmers use the following statement, which I believe is a classic primer:

That’s right! Mentos candy and Coke!

Mentos meets coke, and there’s a violent reaction, where the uncertainty and the number of states on one side is poured directly into the other, and it’s a violent entropy increase

On the left is the state in your application, on the right is the state of the data request you received, and what happens when they try to touch?

Notice that the data and the possibility of changing the data should be treated as states. Entropy itself is a set of state possibilities. So, in addition to the data returned by the request, there are also request return times, errors, multiple requests, race or more complex scheduling?

On one side, you have react applications with deterministic scheduling and deterministic structure, and on the other side, you have asynchronous applications with indeterminate data and indeterminate scheduling

Think of them as a system. How do you solve this problem?

That’s right! Maxwell’s Demon!

This problem can be solved by assuming that a selective subject, Maxwell’s demon, selectively places the results in another structure (the React app/Store)

On one side is the deterministic (low entropy) state, which is well guaranteed by the Reducer selection of Maxwell dispatch

const [state,dispatch] = useReducer((state,action) = >{
  if(action.name === 'xxx') {// Reducer selection is underway
  }
  
  Add state on the other side
  return{... state} },{})Copy the code

Therefore, useReducer is a good solution to the previously mentioned problem of calling callback in response to non-synthetic events

At this point, the immutability of dispatch becomes a good use scenario:

const ws = useRef()
const [state,dispatch] = useReducer((state,action) = >{
  if(action.payload === 'init'){
    ws.current = new WebSocker('... ')}if(action.payload === 'read'){
    ws.current.send('read')}// ...}, {data:' '.error:null})

// In this way, the structure of the application itself can easily communicate (effect) with another part (non-synthetic event)

useEffect(() = >{
  if(ready){
    dispatch('init')
  }
},[ready])


return <button onClick={()= >dispatch('init')}>init</button>
Copy the code

This way, the uncertainty is much lower than if you just used useCallback (because dependencies are hard to handle, or at least brain-burning)

The entropy of the whole application is very well controlled

UseReducer, the magic device for system interconnection

Yes, useReducer is very useful when we want to connect one closed system to another to form a larger closed system, because it controls the uncertainty

Think of Dispatch as Maxwell’s demon, and you can easily isolate multiple systems with predictable results

So, other than asynchrony, where else can you use it?

Cross module communication!

This section can be shared later because it involves an architectural technique that I still don’t fully understand

Can you use useReducer?

It would be, unless you don’t want some fully packaged third-party hooks API and a more straightforward stream

But efficiency and quality can be tradeoff, this part depends on your opinion, but once you use useReducer development, it is the default, there is a useReducer, a separate module

In other words, either use the useReducer entirely or use it only for module communication. (Communication of other scheduling systems can also be regarded as module communication.)