Languages

React - what is the difference between useState and useReducer?

0 points
Asked by:
Dirask Community
5460

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:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = ({initialCount}) => {
  const [count, setCount] = React.useState(0);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}

const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );

useReducer example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const initialState = {count: 0};

function 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 = ({initialCount}) => {
  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 );
1 answer
0 points
Answered by:
Dirask Community
5460

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 comments Add comment
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join