Languages

React - what is the difference between useState and useReducer?

0 points
Asked by:
Fletcher-Peralta
778

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:
Fletcher-Peralta
778

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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