Hooks: concepts and advantages - useState, useEffect, useContext; useRef, useReducer, useCallback, useMemo; building custom hook, advantages and use

Hooks function components को state और logic hold करने देते हैं: state के लिए useState, side effects के लिए useEffect, plus useContext, useRef, useReducer और memoization, और आप logic को अपने खुद के custom hooks में bundle कर सकते हैं।

13 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

एक Function Component कैसे याद रखता है

एक React function component बस एक function है: यह चलता है, JSX return करता है, और सब कुछ भूल जाता है। तो एक counter clicks के बीच अपना count कैसे REMEMBER करता है? FestConnect अपने events को page load होने पर एक बार कैसे FETCH करता है?

Answer है hooks: special functions जो function components को MEMORY और lifecycle powers देते हैं जिनके लिए कभी class components चाहिए होते थे। आप पहले से एक से मिल चुके हैं, useState, form values hold करते हुए। यह lesson hook family cover करता है, वे rules जो इन्हें govern करते हैं, और अपना खुद का logic CUSTOM hooks में कैसे bundle करें। Hooks modern React का core हैं, और ये FestConnect का front-end complete करते हैं।

Theory

useState और useEffect: वो दो जो आप Daily इस्तेमाल करते हैं

useState एक component में STATE add करता है:

const [count, setCount] = useState(0);

count current value है, setCount इसे update करता है, और setCount call करना नई value के साथ एक RE-RENDER trigger करता है। State एक component का अपना changeable data है (read-only props के उलट)।

useEffect component के render होने के बाद SIDE EFFECTS चलाता है (rendering से बाहर की चीज़ें: data fetch करना, timers, subscriptions)। इसका second argument, dependency array, control करता है यह WHEN चलता है:

  • [] (empty): ONCE चलाइए, mount पर: FestConnect के events को load पर fetch करने के लिए perfect
  • [x]: जब भी x बदले चलाइए
  • omitted: हर RENDER के बाद चलाइए (rarely आप जो चाहते हैं)

ये दो ज़्यादातर real components cover करते हैं: याद रखने के लिए state, बाहर की दुनिया तक पहुँचने के लिए effects।

Practical

useState (Counter) और useEffect (Mount पर Fetch)

function EventPage() {
  const [count, setCount] = React.useState(0);      // state
  const [events, setEvents] = React.useState([]);

  // useEffect with [] runs ONCE, after the first render:
  React.useEffect(() => {
    fetch("/api/events")            // hits the MongoDB-backed API
      .then(r => r.json())
      .then(data => setEvents(data));  // updates state -> re-render
  }, []);                            // [] = run once on mount

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Clicked {count} times
      </button>
      <p>{events.length} events loaded</p>
    </div>
  );
}

This example runs in Gri-Learn on the web, where you can edit it and see the output.

At a glance

Hook Family

Hookयह क्या करता है
useStateState add करता है; setter एक re-render trigger करता है
useEffectRender के बाद side effects चलाता है; dependency array timing control करता है
useContextहर level पर props pass किए बिना shared context पढ़ता है
useRefएक value जो renders के across persist करती है re-render कराए बिना (या एक DOM reference)
useReducerएक reducer function के through state, complex state logic के लिए
useCallback / useMemoएक function / एक computed value memoize करता है ताकि needless work से बचा जा सके

Theory

Hooks के Rules, और Custom Hooks

Hooks के 2 unbreakable rules हैं:

  • hooks सिर्फ़ एक component के TOP LEVEL पर call कीजिए, कभी loops, conditions, या nested functions के अंदर नहीं (React इस पर rely करता है कि hooks हर render में same order में call हों)
  • hooks सिर्फ़ React function components से (या दूसरे hooks से) call कीजिए

Custom hooks आपका अपना reusable logic हैं: एक function जिसका नाम use से शुरू होता है और जो दूसरे hooks call करता है। For example, एक useEvents() custom hook fetch-events state और effect को bundle कर सकता है, तो कोई भी component const events = useEvents(); कर सकता है और data पा सकता है। Custom hooks वह तरीका है जिससे आप stateful logic को components के across बिना repeat किए SHARE करते हैं: old class approach पर hooks जो main advantage लाए।

Quiz

आप चाहते हैं FestConnect page पहली बार load होने पर exactly एक बार अपने events fetch करे। आप कौन सी useEffect dependency array इस्तेमाल करते हैं?

  1. कोई second argument नहीं (हर render के बाद चलता है)
  2. एक empty array []: effect once चलता है, mount पर
  3. [events]: यह चलता है जब भी events बदलता है
  4. useEffect control नहीं कर सकता यह कब चले
Show the answer

एक empty array []: effect once चलता है, mount पर

एक empty dependency array [] useEffect को बताता है इसका effect exactly ONCE चलाओ, पहले render के बाद (mount पर): events के one-time fetch के लिए ideal। Option A (कोई array नहीं) effect को हर RENDER के बाद चलाता है, जो endlessly re-fetch करता (और बदतर, setEvents एक render trigger करता है, एक infinite fetch loop cause करते हुए)। Option C ([events]) events बदलने पर हर बार re-run होता, और चूँकि fetch events SET करता है, वह भी loop करता है। Option D false है: dependency array exactly वह तरीका है जिससे आप timing control करते हैं। Rule: once-on-mount के लिए [], when-x-changes के लिए [x], every-render के लिए omitted (rarely wanted)। Fetch-on-load classic [] case है।

Think first

The Infinite Fetch Loop

एक student events fetch करने के लिए useEffect लिखता है पर dependency array पूरी तरह FORGET कर देता है। Network tab same request को endlessly firing दिखाता है। यह क्यों होता है trace कीजिए। फिर tap कीजिए।

Show the answer

बिना dependency array के, useEffect हर RENDER के बाद चलता है। Effect events fetch करता है और setEvents(data) call करता है। पर setEvents STATE UPDATE करता है, जो एक RE-RENDER trigger करता है। Re-render useEffect को फिर से चलाता है (कोई dependency array नहीं = हर render), जो फिर fetch करता है, जो फिर setEvents करता है, जो फिर re-render करता है: server को hammer करता एक infinite loop। Fix है empty dependency array []: यह useEffect को बताता है mount पर ONCE चलो और फिर कभी नहीं, loop तोड़ते हुए। यह सबसे common React beginner bugs में से एक है, और यह dependency array का purpose vividly सिखाता है: यह control करता है effect कब re-run हो, और इसे भूलना मतलब है 'always', जो state updates के साथ combined होकर spiral करता है। useEffect को हमेशा सही dependency array दीजिए।

Watch out

Hooks Traps

Missing/Wrong Dependency Array: कोई array नहीं = हर render (fetch के साथ infinite loops); [] = once; [x] = जब x बदले।

Conditions या Loops में Hooks: hooks के rules तोड़ता है; इन्हें सिर्फ़ top level पर call कीजिए।

State Directly Mutate करना: setter इस्तेमाल कीजिए (setCount), कभी count = ... नहीं; direct mutation re-render नहीं करता।

Stale Closures: एक effect जो पुरानी state value capture करता है: सही dependencies include कीजिए।

Custom Hook 'use' से शुरू न होना: rules apply होने के लिए नाम use से शुरू होना चाहिए।

Theory

Unit 2 Complete: React Front-End Built

FestConnect के पास अब एक modern React front-end है: components और props, events, lists, conditional rendering, controlled forms, और state, effects और reusable logic के लिए hooks, Unit 1 के MongoDB back-end पर बैठा हुआ। यह एक complete modern stack है। Unit 3 दूसरा major front-end framework सिखाता है, Angular, ताकि आप दो industry leaders compare कर सकें। अलग philosophy, same goal: React components की एक library था; Angular एक full framework है, अगला।

Summary

Key takeaways

  • Hooks functions हैं (नाम 'use' से शुरू होते हैं) जो function components को state और lifecycle powers देते हैं।
  • useState state add करता है: [value, setValue] = useState(initial); setter एक re-render trigger करता है।
  • useEffect render के बाद side effects चलाता है; dependency array timing control करता है: [] once, [x] change पर, omitted हर render।
  • Family: useContext (shared context), useRef (re-render के बिना persist / DOM ref), useReducer (complex state), useCallback/useMemo (memoize)।
  • Hooks के rules: सिर्फ़ top level पर call कीजिए, सिर्फ़ React functions से।
  • Custom hooks (functions जो 'use' से शुरू होते हैं और hooks call करते हैं) components के across stateful logic reuse करते हैं।
  • Memory hook: useState याद रखता है, useEffect बाहर पहुँचता है, [] once चलता है।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Fundamentals of React.js

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Hooks: concepts and advantages - useState, useEffect, useContext; useRef, useReducer, useCallback, useMemo; building custom hook, advantages and use · Advance Web Designing (Major-11-01) · Gri-Learn