I
I
IvanIvanIvanIvanIvan2019-03-07 09:39:26
React
IvanIvanIvanIvanIvan, 2019-03-07 09:39:26

Hooks API react. Is it possible to replace state redux using useReducer?

We have three components
1

import React, { useReducer } from 'react';
import { Hook } from './Hook';
export const One = () => {
  const { state, dispatch } = Hook();
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </>
  );
}

2
import React, { useReducer, withContext } from 'react';
import { Hook } from './Hook';
export const Two = () => {
  const { state, dispatch } = Hook();
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </>
  );
}

3 Hook itself
import React, { useReducer } from 'react';
export const
  Hook = () => {
    const initialState = {count: 0};

    const reducer = (state, action) => {
      switch (action.type) {
        case 'increment':
          return {count: state.count + 1};
        case 'decrement':
          return {count: state.count - 1};
        default:
          throw new Error();
      }
    }

    const [state, dispatch] = useReducer(reducer, initialState);

    return { state,  dispatch};
  };

Now, as expected, each of the components works autonomously. The question is the following. Is it possible to somehow force 3 components (hook) to become a common state for the other two? That is, to become a replacement for redux?
Link to code
https://codesandbox.io/s/lxvl2lzxom

https://reactjs.org/docs/hooks-reference.html#usec...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-03-07
@IvanIvanIvanIvanIvan

So , right?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question