EN
React - what is the difference between useState and useReducer?
1 answers
0 points
Hi, can someone explain to me what's the difference between useState and useReducer hook?
React documentation says that "useReducer
is usually preferable to useState
...", so why should I use useReducer
instead of useState
?
useState example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = ({initialCount}) => {
6
const [count, setCount] = React.useState(0);
7
return (
8
<>
9
Count: {count}
10
<button onClick={() => setCount(initialCount)}>Reset</button>
11
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
12
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
13
</>
14
);
15
}
16
17
const root = document.querySelector('#root');
18
ReactDOM.render(<App/>, root );
useReducer example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const initialState = {count: 0};
6
7
function reducer(state, action) {
8
switch (action.type) {
9
case 'increment':
10
return {count: state.count + 1};
11
case 'decrement':
12
return {count: state.count - 1};
13
default:
14
throw new Error();
15
}
16
}
17
18
const App = ({initialCount}) => {
19
const [state, dispatch] = React.useReducer(reducer, initialState);
20
return (
21
<>
22
Count: {state.count}
23
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
24
<button onClick={() => dispatch({type: 'increment'})}>+</button>
25
</>
26
);
27
}
28
29
const root = document.querySelector('#root');
30
ReactDOM.render(<App/>, root );
1 answer
0 points
The useReducer
hook is used to keep a lot of state changes inside it when you have complex state logic. In the useState
the whole state has to be overwritten. Reducer is therefore for smarter condition management. Additionally, it helps to organize the logic of the component.
0 commentsShow commentsAdd comment