Answer the question
In order to leave comments, you need to log in
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>
</>
);
}
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>
</>
);
}
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};
};
https://codesandbox.io/s/lxvl2lzxom
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question