Nearby lessons
15 of 44🪝 ReactJS – Hooks
📌 What are Hooks?
Introduction to Hooks
Hooks allow you to use state and other React features without writing a class. They make function components more powerful by giving them access to features like lifecycle methods. Hooks were introduced in React v16.8 (Feb 16, 2019).
Although Hooks generally replace class components, React has no plans to remove classes. Hooks are an additional feature, not a replacement.
📌 What is a Hook?
- Hooks are functions in React
- They allow us to “hook” into React features such as state and lifecycle methods
- Hooks make function components more powerful without converting them into class components
⚖️ Rules of Hooks
Hooks have some strict rules to follow:
- Hooks can only be used inside React function components
- Always call Hooks at the top level of your component
- Do not use Hooks inside loops, conditions, or nested functions
- Hooks must be called in the same order on every render
- Hooks cannot be used in class components
React Playground
import React, { useState } from "react"; // ❌ Wrong: Normal function function normalFunction() { const [count, setCount] = useState(0); // Not allowed } // ✅ Correct: React Function Component function MyComponent() { const [count, setCount] = useState(0); // Allowed return <p>{count}</p>; } export default MyComponent;
🛑 Common Mistakes with Hooks
- ❌ Using Hooks inside loops or conditions
- ❌ Calling Hooks from normal functions
- ❌ Using Hooks conditionally
- ❌ Using Hooks inside class components
✅ Correct Usage of Hooks
React Playground
import React, { useState } from "react"; function MyComponent() { // Always at top level const [name, setName] = useState(""); const [status, setStatus] = useState(true); return ( <div> <p>Name: {name}</p> <p>Status: {status ? "Active" : "Inactive"}</p> </div> ); } export default MyComponent;
⚙️ Custom Hooks
If you have stateful logic that needs to be reused in several components, you can create your own custom Hooks.
Example: useForm, useAuth, useFetch, etc.
📚 Commonly Used Hooks
- useState – for managing state
- useEffect – for side effects (API calls, subscriptions, timers, etc.)
- useContext – for accessing context API
- useRef – for referencing DOM elements or persisting values
- useReducer – for complex state logic
- useCallback – for memoizing functions
- useMemo – for memoizing values
- Custom Hooks – user-defined hooks
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4
Keep Going!React - useState Hook