← Back to React Course | Chapter 5: Core Hooks | Lesson 5 of 12

useReducer Hook का उपयोग

useReducer state के लिए एक vending machine जैसा है -- आप एक action insert करते हैं, और rules का एक single set exactly decide करता है कि नई state क्या होनी चाहिए।
Syntax
markup
function reducer(state, action) {
  switch (action.type) {
    case "actionType":
      return newState;
    default:
      return state;
  }
}

const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: "actionType" });

Writing a Reducer Function

एक reducer एक plain function है जो current state और एक action लेता है, फिर नई state return करता है -- कुछ-कुछ जैसे Array.reduce काम करता है।

यह state कैसे change होती है इसकी सारी logic एक जगह centralize करता है, component में setter calls scatter करने के बजाय।

Note: एक reducer को हमेशा एक brand-new state object/value return करना चाहिए, कभी उसे mutate नहीं करना चाहिए जो इसे मिला।
Warning: एक default: return state; case भूल जाने का मतलब है कि एक unrecognized action type dispatch करना silently कुछ नहीं करता, जो debug करना confusing हो सकता है।

उदाहरण: Writing a Reducer Function

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function counterReducer(state, action) {
      switch (action.type) {
        case "increment": return state + 1;
        case "decrement": return state - 1;
        default: return state;
      }
    }
    function Counter() {
      const [count, dispatch] = React.useReducer(counterReducer, 0);
      return (
        <div>
          <p>{count}</p>
          <button onClick={() => dispatch({ type: "increment" })}>+</button>
          <button onClick={() => dispatch({ type: "decrement" })}>-</button>
        </div>
      );
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<Counter />);
  </script>
</body>
</html>

Dispatching Actions

एक setter function directly call करने के बजाय, useReducer आपको एक dispatch function देता है -- आप इसे यह describe करने वाले एक action object के साथ call करते हैं कि क्या हुआ, और reducer decide करता है कि response में state कैसे change होनी चाहिए।

यह 'क्या हुआ' को 'इसकी वजह से state कैसे change होती है' से अलग करता है।

Note: Action objects conventionally एक type field रखते हैं जो event describe करता है, plus reducer को चाहिए कोई भी extra data (एक payload)।
Warning: Dispatch directly state set नहीं करता -- यह reducer function है जो action से actual नई state compute करता है।

उदाहरण: Dispatching Actions

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function reducer(state, action) {
      switch (action.type) {
        case "setName": return { ...state, name: action.payload };
        default: return state;
      }
    }
    function NameForm() {
      const [state, dispatch] = React.useReducer(reducer, { name: "" });
      return (
        <div>
          <input onChange={(e) => dispatch({ type: "setName", payload: e.target.value })} />
          <p>Name: {state.name}</p>
        </div>
      );
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<NameForm />);
  </script>
</body>
</html>

When to Choose useReducer over useState

useReducer तब shine करता है जब एक component की state में कई related values शामिल हों जो साथ change होती हैं, या जब next state पिछली state पर based complex logic पर depend करती है। Simple, independent values के लिए, useState अब भी simpler और ज़्यादा direct रहता है।

Note: अगर आपको लगे कि एक component के state updates में काफी interconnected if logic शामिल है, तो यह एक signal है कि useReducer इसे कई useState calls से बेहतर organize कर सकता है।
Warning: एक single boolean toggle या simple counter के लिए useReducer का उपयोग करना एक plain useState के मुकाबले unnecessary complexity जोड़ता है।

उदाहरण: When to Choose useReducer over useState

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function formReducer(state, action) {
      switch (action.type) {
        case "updateField": return { ...state, [action.field]: action.value };
        case "reset": return { name: "", email: "" };
        default: return state;
      }
    }
    function SignupForm() {
      const [state, dispatch] = React.useReducer(formReducer, { name: "", email: "" });
      return (
        <div>
          <input placeholder="Name" onChange={(e) => dispatch({ type: "updateField", field: "name", value: e.target.value })} />
          <p>Name: {state.name}</p>
        </div>
      );
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<SignupForm />);
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक reducer function लिखना जो नई brand-new state object return करने के बजाय existing state को mutate करता है।
  2. Reducer की switch statement में एक default case शामिल करना भूल जाना, unknown actions को silently ignore करते हुए।
  3. बहुत simple state के लिए useReducer का उपयोग करना जिसे एक plain useState बराबर अच्छी तरह handle कर लेता।
चैप्टर सारांश
  • useReducer ज़्यादा complex state logic manage करने के लिए useState का एक alternative है।
  • यह एक reducer function और initial state लेता है, current state और एक dispatch function return करते हुए।
  • आप action objects dispatch करके state update करते हैं, directly setter call करके नहीं।
  • यह खासतौर पर तब useful है जब state updates कई related pieces of logic पर depend करते हैं।
ब्राउज़र सपोर्ट

React 16.8 से available है, जब Hooks introduce हुए थे।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.