React Hooks - Simple Notes
What is a Hook?
Hooks are functions in React that let you use state and other features inside functional
components. Always start with 'use' (example: useState, useEffect).
Types of Hooks (Syntax + Example)
1. useState → for state
Syntax:
const [state, setState] = useState(initialValue);
Example:
const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1)}>Click</button>
2. useEffect → for side effects (API call, timer)
Syntax:
useEffect(() => {
// code
return () => { /* cleanup */ }
}, [dependencies]);
Example:
useEffect(() => {
console.log('Component mounted');
}, []);
3. useContext → for global values (no props drilling)
Syntax:
const value = useContext(MyContext);
Example:
const theme = useContext(ThemeContext);
4. useRef → for DOM reference or store values
Syntax:
const ref = useRef(initialValue);
Example:
<input ref={inputRef} />
5. useMemo → memoize/calculation optimization
Syntax:
const memoValue = useMemo(() => compute(), [deps]);
Example:
const result = useMemo(() => num * 2, [num]);
6. useCallback → memoize functions
Syntax:
const memoFunc = useCallback(() => { code }, [deps]);
Example:
const add = useCallback(() => setCount(c => c+1), []);
7. Custom Hook → your own reusable hook
Syntax:
function useMyHook() {
// use other hooks
return value;
}
Example:
function useWindowWidth() { ... }
Difference Between Hooks
- useState → data storage
- useEffect → lifecycle / side effects
- useContext → global values
- useRef → DOM or non-render values
- useMemo → optimize calculation
- useCallback → optimize function
- Custom Hook → reusable logic
Common Interview Questions
1. What are hooks and why introduced?
2. Difference between useState and useRef.
3. How dependency array works in useEffect.
4. Difference between useMemo and useCallback.
5. How to create a custom hook?
6. Why hooks should not be used inside loops or conditions?
7. Difference between lifecycle methods (class) vs useEffect.
What is a Hook in React?
Hooks are special functions introduced in React 16.8.
They let you use state and lifecycle features in functional components (without
writing class components).
Hooks always start with the word use (example: useState, useEffect).
👉 Simply: Hooks make functional components powerful by giving them the ability to
remember data, react to changes, and more.
🔹 Types of Hooks
1. useState Hook
👉 Used to manage state (data) inside functional components.
Syntax:
const [state, setState] = useState(initialValue);
Example:
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0); // state variable
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
✅ Explanation:
count → stores current value
setCount → function to update value
When button clicked, state changes and UI re-renders.
2. useEffect Hook
👉 Used to handle side effects like fetching data, timers, subscriptions.
Syntax:
useEffect(() => {
// code (side effect)
return () => {
// cleanup code
};
}, [dependencies]);
Example:
import React, { useState, useEffect } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
return () => clearInterval(interval); // cleanup
}, []);
return <p>Seconds passed: {seconds}</p>;
}
✅ Explanation:
Runs once after component mounts ([] dependency).
Updates seconds every second.
Cleans up interval when component unmounts.
3. useContext Hook
👉 Used for global state management without props drilling.
Syntax:
const value = useContext(MyContext);
Example:
import React, { createContext, useContext } from "react";
const ThemeContext = createContext("light");
function Child() {
const theme = useContext(ThemeContext);
return <p>Theme is {theme}</p>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<Child />
</ThemeContext.Provider>
);
}
✅ Explanation:
Instead of passing theme as props, useContext gets it directly.
4. useRef Hook
👉 Used to reference DOM elements or store values that don’t cause re-render.
Syntax:
const refName = useRef(initialValue);
Example:
import React, { useRef } from "react";
function InputFocus() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus(); // focus DOM element
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
✅ Explanation:
useRef stores reference of <input>.
Clicking button focuses input box.
5. useMemo Hook
👉 Used for performance optimization (memoizes expensive calculations).
Syntax:
const memoValue = useMemo(() => computeFunction(), [dependencies]);
Example:
import React, { useState, useMemo } from "react";
function ExpensiveCalculation({ num }) {
const result = useMemo(() => {
console.log("Calculating...");
return num * 2;
}, [num]);
return <p>Result: {result}</p>;
}
✅ Explanation:
useMemo caches the result until num changes.
Prevents re-calculating every render.
6. useCallback Hook
👉 Used to memoize functions (avoid re-creating function every render).
Syntax:
const memoFunc = useCallback(() => {
// function code
}, [dependencies]);
Example:
import React, { useState, useCallback } from "react";
function Counter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []);
return (
<div>
<p>{count}</p>
<button onClick={increment}>Increase</button>
</div>
);
}
✅ Explanation:
increment function will not be re-created unnecessarily.
Helps in child components that depend on function props.
7. Custom Hooks
👉 You can build your own hook by combining other hooks.
Rule: Custom hook must start with use.
Example:
import { useState, useEffect } from "react";
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
function App() {
const width = useWindowWidth();
return <p>Window width: {width}</p>;
}
✅ Explanation:
useWindowWidth is a custom hook that tracks window size.
Can be reused anywhere.
🔹 Difference Between Hooks
Hook Purpose
useState Manage state (data) inside component
useEffect Handle side effects (API calls, timers)
useContext Access global values without props
useRef Reference DOM elements / store values without re-render
useMemo Optimize expensive calculations
useCallback Optimize function definitions
Custom Hook Reusable logic across components
🔹 Common Interview Questions (Top MNCs)
1. What are hooks in React? Why were they introduced?
2. Difference between useState and useRef.
3. How does useEffect dependency array work?
4. What is the difference between useMemo and useCallback?
5. How do you create a custom hook? Give an example.
6. Why can’t we use hooks inside loops or conditions?
7. Difference between class lifecycle methods and useEffect.
8. When to use context instead of props?
9. What happens if you don’t provide a dependency array in useEffect?
10. How do hooks improve performance?
What are hooks in React? Why were they introduced?
Hooks are functions that let you “hook into” React state and lifecycle in
functional components.
Introduced in React 16.8 to:
o Avoid class components for simple state/lifecycle needs.
o Share logic between components easily (via custom hooks).
o Make code cleaner, reusable, and easier to test.
2️⃣ Difference between useState and useRef
Feature useState useRef
Purpose Manage state and trigger re-render Store mutable value without re-render
Updates Causes component to re-render Does not trigger re-render
Use case UI data, counters, forms DOM reference, timers, previous state storage
Example:
const [count, setCount] = useState(0); // UI updates on change
const inputRef = useRef(null); // reference DOM without re-
render
3️⃣ How does useEffect dependency array work?
Dependency array tells React when to run the effect.
o [] → run only once (componentDidMount).
o [var1, var2] → run when any dependency changes.
o No array → run on every render.
Example:
useEffect(() => {
console.log("Runs when count changes");
}, [count]);
4️⃣ Difference between useMemo and useCallback
Feature useMemo useCallback
Returns Memoized value Memoized function
Use case Expensive calculations Prevent re-creating functions on re-render
Feature useMemo useCallback
Caches result until dependencies Caches function reference until
Performance
change dependencies change
5️⃣ How do you create a custom hook? Give an example.
Custom Hook is a reusable function that may use other hooks.
Must start with use.
Example:
import { useState, useEffect } from "react";
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
// Usage in component
function App() {
const width = useWindowWidth();
return <p>Window width: {width}</p>;
}
6️⃣ Why can’t we use hooks inside loops or conditions?
Rules of Hooks: Always call hooks at the top level of the functional component.
Reason: React relies on call order to preserve state between renders.
Violating this leads to unpredictable behavior and errors.
7️⃣ Difference between class lifecycle methods and useEffect
Feature Class Component Functional Component (useEffect)
Mount componentDidMount useEffect(() => {}, [])
Feature Class Component Functional Component (useEffect)
Update componentDidUpdate useEffect(() => {}, [deps])
Unmount componentWillUnmount useEffect(() => { return cleanup }, [])
Multiple effects Hard to split logic Can have multiple useEffect hooks
8️⃣ When to use context instead of props?
Use Context API to avoid prop drilling when passing data through multiple
component levels.
Example: theme, authentication state, language settings.
9️⃣ What happens if you don’t provide a dependency array in useEffect?
The effect runs after every render, causing:
o Repeated side-effects (like API calls).
o Potential performance issues or infinite loops if effect updates state.
🔟 How do hooks improve performance?
Avoid unnecessary class components and boilerplate.
useMemo and useCallback prevent re-calculation and re-creation on every
render.
useRef allows storing values without triggering re-render.
Overall: cleaner code, optimized re-renders, reusable logic.