EN
React - useReducer vs useState example
0
points
In this article, we would like to compare two React hooks - useReducer
and useState
.
We use useReducer
to keep a lot of state changes inside it. In the useState
, the whole state has to be overridden. Reducer is therefore for smarter condition management. Additionally, it organizes the logic of the component.
Below we have a similar solution to the one in React documentation. What we're going to do is try to manage the state the same way the reducer
function does but with a simple useState
hook.
For the simplicity of the example, we've made an increasing and decreasing counter. We perform actions handled by the reducer function that modifies the current state.
useReducer
example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
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 App = () => {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
useState
example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const [state, setState] = React.useState(0);
const handleClick = (type) => {
switch (type) {
case 'increment':
setState((state) => state + 1);
break;
case 'decrement':
setState((state) => state - 1);
break;
default:
throw new Error(type);
}
};
return (
<>
Count: {state}
<button onClick={() => handleClick('decrement')}>-</button>
<button onClick={() => handleClick('increment')}>+</button>
</>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );