Complete Guide to React Hooks

Interview-focused notes with practical code examples.

What are components in React?

A component is a JavaScript function that returns JSX.

What are hooks?

Hooks are special functions that give power (state, effects) to React function components.

Props

Props (short for properties) are read-only values passed from a parent component to a child component.

useState

useState is used to store and manage data inside a component. When state is updated, React re-renders the component and updates the UI.

tsx
const [state, setState] = useState(initialValue);

Virtual DOM, Diffing, and Reconciliation

useEffect

useEffect runs side effects like API calls, event listeners, DOM updates, and subscriptions.

tsx
import { useEffect } from "react";
function App() {
useEffect(() => {
function handleResize() {
console.log("Window resized");
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return <h1>Resize the window</h1>;
}

useRef

Fragments

Fragments let you return multiple elements without adding extra DOM nodes.

Lifting State Up

Move shared state to the nearest common parent so multiple children can use and update it.

tsx
function Parent() {
const [count, setCount] = useState(0);
return (
<>
<ChildA onIncrement={() => setCount((c) => c + 1)} />
<ChildB onDecrement={() => setCount((c) => c - 1)} />
<p>Count: {count}</p>
</>
);
}

useMemo and useCallback

useContext

useContext avoids prop drilling by sharing global-like data without passing props at every level.

Redux Interview Notes

Redux flow diagram

Put your provided Redux image in public/Redux.png to show it here.

Redux Core Principles

  1. Single source of truth: one store for app state.
  2. State is read-only: change only through actions.
  3. Reducers are pure functions that return new state.

createAsyncThunk

createAsyncThunk handles API calls in Redux with loading, success, and error states.

tsx
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
export const fetchUsers = createAsyncThunk("users/fetch", async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
return res.json();
});
const usersSlice = createSlice({
name: "users",
initialState: { items: [], loading: false, error: null as string | null },
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchUsers.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(fetchUsers.fulfilled, (state, action) => {
state.loading = false;
state.items = action.payload;
})
.addCase(fetchUsers.rejected, (state) => {
state.loading = false;
state.error = "Failed to fetch users";
});
},
});