React JS में कस्टम हुक्स | व्याख्यान 16 | React JS से शुरुआत से (हिंदी में)

Posted by

Custom Hooks in React JS | Lecture 16 | React JS from scratch

Custom Hooks in React JS | Lecture 16 | React JS from scratch

React JS में Custom Hooks का इस्तेमाल ऐसे functionality को रियाल्यूज करने के लिए किया जाता है जो किसी भी Component में दोबारा और दोबारा बार-बार लिखने की जरूरत न हो। इससे Code को रीफैक्टर करने में भी मदद मिलती है और Code को maintain करना भी आसान हो जाता है।

Custom Hooks को बनाने के लिए हमने उन्हें hooks की तरह ही लिखना होता है, लेकिन उसका नाम use के साथ शुरू करना पड़ता है। जैसे useFetch, useAsync इत्यादि।

एक example के रूप में, हम एक useCounter hook बना सकते हैं जो किसी Component में counter की state को हेंडल करेगा।


function useCounter(initialValue) {
   const [count, setCount] = useState(initialValue);
   const increment = () => {
     setCount(count + 1);
   }
   const decrement = () => {
     setCount(count - 1);
   }
   return {
     count,
     increment,
     decrement
   }
}

इसके बाद, हम useCounter hook का इस्तेमाल किसी Component में इस तरह से कर सकते हैं:


function CounterComponent() {
   const {count, increment, decrement} = useCounter(0);
   return (
     <div>
       <p>Count: {count}</p>
       <button onClick={increment}>Increment</button>
       <button onClick={decrement}>Decrement</button>
     </div>
   )
}

इस तरह, हमने useCounter hook को use करके Component में counter functionality को encapsulate किया है। यह Code को clean और maintainable बनाने में मदद करता है।

इसी तरह, हम Custom Hooks का इस्तेमाल अन्य functionality को हेंडल करने के लिए भी कर सकते हैं।

0 0 votes
Article Rating

Leave a Reply

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x