In React, props (short for properties) are used to pass data from one component to another, usually from a parent component to a child component.
Props help you create reusable components by allowing the same component to display different data.
- strings
- Number
- Boolean
- arrays
- object
- function
- children
- jsx/ component
In React, default props are the default values assigned to a component's props when the parent component does not provide those props, or provides undefined.
-----Guest ----Guest -----Amit ------Nothing visible --------Empty string
Because JavaScript default parameters apply only when the value is undefined, not when it is null, an empty string, false, or 0.
Default props are useful for several reasons:
Avoid undefined values: A component can display meaningful content even when a prop is omitted.
Improve reusability: You can reuse a component without specifying every property each time.
Simplify code: You don't need to write separate conditions for every missing prop.
Provide sensible defaults: Buttons, cards, user profiles, and other components can have standard values.
-
Props are read-only. A child component should not directly modify the props it receives.
-
Props flow from parent to child. To communicate changes back to a parent, a child can call a function passed as a prop.
-
Props can have default values. For example, function Welcome({ name = "Guest" }).
-
Props can be any JavaScript value, including strings, numbers, objects, arrays, functions, and JSX elements.
-
Props are different from state. Props are passed into a component; state is data managed by a component and can change over time.
JSX stands for JavaScript XML.
JSX is a syntax extension for JavaScript that allows us to write HTML-like markup inside JavaScript code when building user interfaces with React.
- Return a single enclosing element
- Close all tags
- Use camelCase for many attributes
- class and for attributes are changed to className and htmlFor.
- use JSX Expression to access js inside JSX
- we can't declare a variable inside the jsx expression
- we can initialization | re-initialization inside
- we can't use conditional statements. Only ternary operator
- we can't use loops . only map we can use.
- we can execute the js expressions inside the jsx Expression
- What Is Conditional Rendering? Conditional rendering in React.js means displaying different UI elements or components based on a condition.
In simple words, React renders a particular element when a specified condition is true and may render a different element when the condition is false.
Conditional rendering works similarly to conditional statements in JavaScript, such as:
if if...else Ternary operator (? :) Logical AND (&&) Logical OR (||) switch statements
Conditional rendering is useful when an application needs to display different content depending on the current situation.
Common use cases include:
- Showing login or logout buttons.
- Displaying different content for authenticated and unauthenticated users.
- Showing loading indicators while fetching data.
- Displaying error messages when something goes wrong.
- Showing success messages after submitting a form.
- Displaying products based on availability.
- Showing or hiding a modal, dropdown, or menu.
- Rendering different components based on user roles.
- Displaying a message when a list is empty.
- Showing validation errors when form inputs are invalid.
React supports several ways to conditionally render elements. The most common methods are:
Method Best use case
- if...else Multiple statements or complex conditions
- Ternary operator (? :) Choosing between two UI elements
- Logical AND (&&) Rendering something only when a condition is true
- Logical OR (||) Providing a fallback value
- switch statement Choosing among multiple alternatives
Conditional rendering is the process of displaying different UI elements or components based on conditions, using JavaScript expressions and statements.
The most common operators are the ternary operator (? :), logical AND (&&), and logical OR (||). React components can also use if...else and switch statements.
&& is suitable when you want to render something only if a condition is true. A ternary operator is suitable when you want to render one element if a condition is true and another if it is false.
No. A regular if...else statement cannot be placed directly inside a JSX expression. Instead, use it outside the returned JSX or use a ternary expression or logical AND inside JSX.
The expression evaluates to the falsy value on the left, such as false or null. React does not display Boolean values as text. However, if the left side is 0, React displays 0.
Yes. For example:
jsx {isLoggedIn ? : }
Yes. When state changes, React renders the component again and evaluates the conditional expressions using the updated state.
Conditional rendering can omit an element from the rendered DOM. CSS hiding generally keeps the element mounted but makes it invisible.
Yes. You can combine conditions with logical operators, use ternary expressions, or use if...else and switch statements.
They make code harder to read, debug, and maintain. For complicated conditions, use early returns, if...else, or helper functions.
The nullish coalescing operator (??) returns the right-hand side operand only when the left-hand side operand is strictly null or undefined.
useStateis a React Hook used to add and manage state in functional components.- State is data that can change over time and affect what is displayed on the UI.
- When state changes, React re-renders the component to display the updated data.
useStatewas introduced in React 16.8.
const [state, setState] = useState(initialValue);useState- React Hook used to manage state.state- Current state value.setState- Function used to update the state.initialValue- Initial value of the state.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;useStateis a React Hook.- It is used to manage state in functional components.
- It returns an array containing two values:
- The current state.
- A function to update the state.
- The initial state is provided as an argument to
useState(). - Updating state schedules a re-render of the component.
- Never update state directly; use its setter function.
- State updates may be batched by React.
- State updates are not guaranteed to be immediately reflected in the current render.
- State can store numbers, strings, booleans, arrays, objects, and other values.
- Each call to
useStatemanages a separate state variable. - Hooks must be called at the top level of a React component or custom Hook.
- Do not call Hooks inside loops, conditions, or nested functions.
- The initial value is used when the component initializes, not on every re-render.
- React compares the next state with the current state using
Object.is. - When updating objects or arrays, create a new object or array instead of mutating the existing state.
const [count, setCount] = useState(0);
setCount(10);setCount((prevCount) => prevCount + 1);- Use the functional updater when the next state depends on the previous state.
- React processes queued updater functions to calculate the next state.
const [age, setAge] = useState(25);const [name, setName] = useState("John");const [isVisible, setIsVisible] = useState(true);const [items, setItems] = useState([]);const [user, setUser] = useState({
name: "John",
age: 25
});setUser((prevUser) => ({
...prevUser,
age: 26
}));setItems((prevItems) => [...prevItems, "New Item"]);- Use the spread operator (
...) to preserve existing properties or elements. - Avoid mutating state directly with operations such as assigning object properties or using
push()on the existing state array.
- If calculating the initial state is expensive, pass a function to
useState.
const [value, setValue] = useState(() => {
return calculateInitialValue();
});- React uses the function's returned value as the initial state.
- In development Strict Mode, React may call the initializer more than once to help detect unintended side effects.
- Changing state directly instead of using the setter function.
- Mutating objects or arrays stored in state.
- Expecting state to change immediately after calling the setter.
- Using the current state value when multiple updates depend on previous values.
- Calling
useStateinside conditions, loops, or nested functions. - Using Hooks outside a function component or custom Hook.
- Forgetting to import
useStatewhen needed.
| State | Normal Variable |
|---|---|
Managed using React Hooks such as useState |
Declared using let, const, or var |
| Updating state schedules a re-render | Changing a normal variable does not trigger a re-render |
| State is retained between renders | A local variable is recreated when the component function runs again |
| Used for data that affects the UI | Used for temporary calculations or values |
- Managing input field values.
- Creating counters.
- Showing or hiding elements.
- Managing dropdowns and modals.
- Tracking checkbox and toggle values.
- Storing selected items.
- Managing simple component-level data.
- Updating UI based on user interactions.
- Definition:
useStatemanages state in React functional components. - Syntax:
const [state, setState] = useState(initialValue); - State update:
setState(newValue); - Previous state update:
setState(prev => nextValue); - Main benefit: React re-renders the component when state changes.
- Important rule: Never mutate state directly.
- Hook rule: Call
useStateonly at the top level of a component or custom Hook.
useRefis a React Hook used to store a mutable value that persists between renders.- It can also be used to access and interact with DOM elements directly.
- Updating a ref does not trigger a re-render of the component.
useRefreturns an object containing acurrentproperty.
const ref = useRef(initialValue);useRef- React Hook used to create a ref object.initialValue- The initial value assigned toref.current.ref- The returned ref object.ref.current- The property used to read or update the stored value.
import { useRef } from "react";
function App() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleFocus}>
Focus Input
</button>
</div>
);
}
export default App;useRef(null)creates a ref object.- The
refattribute connects the ref to the input element. - React assigns the input DOM element to
inputRef.currentafter the element is mounted. - When the button is clicked,
inputRef.current.focus()focuses the input field. - Updating or using the ref does not itself trigger a re-render.
useRefis a React Hook.- It can store mutable values between renders.
- It returns an object with a
currentproperty. - The initial value is passed as an argument to
useRef(). - Updating
ref.currentdoes not trigger a re-render. - The same ref object is retained across renders of the component.
- It can be used to access DOM elements.
- It can store values such as timer IDs, previous values, and mutable counters.
- It should be called at the top level of a function component or custom Hook.
- Changing
ref.currentdoes not automatically update the UI. - Do not use refs as a replacement for state when a value needs to be displayed and updated in the UI.
- In React Strict Mode, components may render more than once in development; avoid relying on a particular ref object created during a discarded render.
- Read or write refs in event handlers and effects rather than during rendering, except for predictable initialization patterns.
import { useRef, useState } from "react";
function App() {
const countRef = useRef(0);
const [renderCount, setRenderCount] = useState(0);
function increaseRef() {
countRef.current += 1;
console.log(countRef.current);
}
return (
<div>
<p>Ref value: {countRef.current}</p>
<button onClick={increaseRef}>
Increase Ref
</button>
<button onClick={() => setRenderCount(c => c + 1)}>
Re-render Component
</button>
</div>
);
}
export default App;- Clicking Increase Ref changes the ref value but does not trigger a re-render.
- Therefore, the displayed ref value may remain unchanged.
- Clicking Re-render Component causes another render, allowing the updated ref value to appear.
- Use
useStateinstead if the UI must update immediately when the value changes.
- Accessing DOM elements.
- Focusing an input field.
- Playing or pausing media through DOM methods.
- Storing timer IDs returned by
setTimeoutorsetInterval. - Keeping mutable values between renders.
- Storing previous values for comparison.
- Integrating with third-party libraries that require DOM references.
| useRef | useState |
|---|---|
| Stores a mutable value | Stores component state |
Updating .current does not trigger a re-render |
Updating state schedules a re-render |
| Useful for DOM access and values not needed for rendering | Useful for values displayed in the UI |
| The same ref object persists between renders | The state value persists between renders |
Changes are mutable through .current |
Updates are made through the setter function |
| useRef | createRef |
|---|---|
| Commonly used in function components | Commonly used in class components |
| Returns a stable ref object across renders | Creates a new ref object whenever called |
| Suitable for storing persistent mutable values | Usually unsuitable for creating refs inside a function component on every render |
- Expecting a ref update to trigger a re-render.
- Using
useRefinstead ofuseStatefor visible UI data. - Accessing a DOM ref before the element is mounted.
- Forgetting to attach the ref to the intended DOM element.
- Reading or changing refs during rendering in ways that cause unpredictable behavior.
- Assuming
ref.currentalways contains a DOM element; it may initially benull.
- Definition:
useRefstores a mutable value that persists between renders. - Syntax:
const ref = useRef(initialValue); - Access the value:
ref.current - Main advantage: Updating the ref does not trigger a re-render.
- Common use: Accessing DOM elements directly.
- Use
useStatewhen a change must update the UI. - Use
useRefwhen a value must persist but changing it should not itself update the UI.
- Props drilling is the process of passing props from a parent component to a deeply nested child component through multiple intermediate components.
- Intermediate components pass the props even when they do not use the data themselves.
- It is also known as "prop drilling."
function App() {
const username = "John";
return <Parent username={username} />;
}
function Parent({ username }) {
return <Child username={username} />;
}
function Child({ username }) {
return <GrandChild username={username} />;
}
function GrandChild({ username }) {
return <h1>Hello, {username}!</h1>;
}
export default App;Appcreates theusernamedata.ApppassesusernametoParent.Parentpasses it toChild.Childpasses it toGrandChild.GrandChilduses the data to display the username.
Important: Parent and Child only pass the prop; they do not use it themselves. This is props drilling.
- Props drilling means passing props through multiple levels of components.
- Props are used to share data between React components.
- The data usually flows from parent components to child components.
- Intermediate components may pass props without using them.
- Props drilling can make code harder to maintain as an application grows.
- It can make components more tightly coupled to the data they pass through.
- Props drilling is not always bad; for a small component tree, it can be simple and appropriate.
- React Context can help avoid passing the same props through many intermediate components.
- State management libraries such as Redux or Zustand can help manage shared state in larger applications.
- Component composition can sometimes eliminate the need for props drilling.
- Too many props must be passed through intermediate components.
- Changes to data requirements can affect several components.
- Code can become harder to read and maintain.
- Components may receive props they do not need.
- Reusing intermediate components in different contexts can become more difficult.
React Context allows components to access shared data without explicitly passing props through every intermediate component.
import { createContext, useContext } from "react";
const UserContext = createContext();
function App() {
return (
<UserContext.Provider value="John">
<Parent />
</UserContext.Provider>
);
}
function Parent() {
return <Child />;
}
function Child() {
return <GrandChild />;
}
function GrandChild() {
const username = useContext(UserContext);
return <h1>Hello, {username}!</h1>;
}
export default App;createContext()creates a context.Providermakes a value available to descendant components.useContext()reads the nearest matching context value.- Intermediate components no longer need to pass the username prop.
- Redux
- Zustand
- MobX
These libraries can help manage shared state across many components when the application requires it.
- Pass components or JSX as
childrenor other props. - This can reduce the need for intermediate components to know about specific data.
| Props Drilling | Context API |
|---|---|
| Data is passed through props at each level | Descendant components can read shared context |
| Intermediate components pass props | Intermediate components do not need to pass context values |
| Suitable for simple component trees | Useful for data shared across many levels |
| Explicit data flow through component interfaces | Data dependency is less visible in component props |
| Can become cumbersome with many levels | Can simplify shared data access |
- When the same data must pass through many intermediate components.
- When many unrelated components need access to the same data.
- When prop passing makes components unnecessarily complex.
- Definition: Passing props through multiple levels of components to reach a deeply nested component.
- Main problem: Intermediate components pass data they do not use.
- Common solution: React Context API.
- Other solutions: Component composition and state management libraries.
- Important note: Props drilling is not inherently bad; use the simplest approach that fits the component tree.
React.memo is a Higher-Order Component (HOC) in React that is used to optimize the performance of functional components.
It prevents unnecessary re-rendering of a component when its props have not changed.
In simple words:
React.memo remembers the previous rendered result of a component and reuses it if the props remain the same.
const MemoizedComponent = React.memo(Component);Or:
import React, { memo } from "react";
const MemoizedComponent = memo(Component);import React from "react";
function Child({ name }) {
console.log("Child component rendered");
return <h2>Hello {name}</h2>;
}
export default Child;If the parent component re-renders, the Child component also re-renders, even if its props have not changed.
import React, { memo } from "react";
function Child({ name }) {
console.log("Child component rendered");
return <h2>Hello {name}</h2>;
};
export default React.memo(Child);Now, if the parent component re-renders but the name prop remains the same, React can skip rendering the Child component.
React.memo compares the previous props with the new props.
- If props are the same, React skips re-rendering the component.
- If props are different, React re-renders the component.
By default, React.memo uses shallow comparison (Object.is) for each prop.
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<Child name="John" />
</div>
);
}
export default Parent;
import React, { useState, memo } from "react";
const Child = ({ name }) => {
console.log("Child Rendered");
return <h2>Hello {name}</h2>;
};
export default React.memo(Child)When the button is clicked:
- Parent component re-renders.
- Count value increases.
- Child component does not re-render because its
nameprop is unchanged.
- Prevents unnecessary component re-renders.
- Improves performance in suitable cases.
- Useful for components that render frequently.
- Helps optimize large React applications.
- Reduces unnecessary rendering work.
- Adds a small comparison overhead.
- Not useful for every component.
- Can make code more complex.
- Does not prevent re-renders caused by a component's own state changes.
- Does not prevent re-renders caused by consumed context changes.
- React.memo is used with functional components.
- It is a Higher-Order Component (HOC).
- It performs shallow comparison of props by default.
- It skips rendering when props are unchanged.
- It does not stop re-renders caused by internal state or context changes.
- New object, array, or function references can cause re-rendering.
- React.memo is a performance optimization, not a guarantee that a component will never re-render.
| Feature | Purpose |
|---|---|
| React.memo | Memoizes a component |
| useMemo | Memoizes a calculated value |
| useCallback | Memoizes a function reference |
// React.memo
const Child = React.memo(ChildComponent);
// useMemo
const result = useMemo(() => {
return a + b;
}, [a, b]);
// useCallback
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);Use React.memo when:
- A component renders frequently.
- Its props often remain unchanged.
- Rendering the component is expensive.
- Profiling shows unnecessary re-rendering.
Avoid using React.memo everywhere because memoization also has a cost.
Q1. What is React.memo?
React.memo is a Higher-Order Component used to optimize functional components by skipping unnecessary re-renders when props remain unchanged.
Q2. Does React.memo prevent all re-renders?
No. It only helps skip re-renders caused by unchanged props. State and context changes can still trigger re-renders.
Q3. What comparison does React.memo use?
It uses shallow comparison of props using Object.is by default.
Q4. Can React.memo work with class components?
React.memo is designed for function components. For class components, React provides PureComponent.
Q5. What is the difference between React.memo and useMemo?
React.memo memoizes a component, whereas useMemo memoizes a calculated value.
Q6. Is React.memo always beneficial?
No. It is useful when the cost of rendering is greater than the cost of comparing props.
React.memo is a React performance optimization technique that prevents unnecessary re-rendering of functional components when their props have not changed.
It is especially useful when working with large applications and expensive components.
useMemo is a React Hook used to memoize (cache) the result of a calculation.
It helps improve performance by avoiding unnecessary recalculations when a component re-renders.
In simple words:
useMemo remembers the calculated value and recalculates it only when its dependencies change.
const memoizedValue = useMemo(() => {
return calculation;
}, [dependencies]);useMemo- React Hook used for memoization.() => {}- Function containing the calculation.dependencies- Values that determine when recalculation is required.memoizedValue- Stores the calculated result.
import React, { useState } from "react";
function App() {
const [count, setCount] = useState(0);
const [number, setNumber] = useState(5);
const expensiveCalculation = () => {
console.log("Calculating...");
let result = 0;
for (let i = 0; i < 1000000000; i++) {
result += i;
}
return number * 2;
};
const result = expensiveCalculation();
return (
<div>
<h2>Count: {count}</h2>
<h2>Result: {result}</h2>
<button onClick={() => setCount(count + 1)}>
Increment Count
</button>
<button onClick={() => setNumber(number + 1)}>
Change Number
</button>
</div>
);
}
export default App;Whenever the component re-renders, the expensive calculation runs again, even if number has not changed.
import React, { useState, useMemo } from "react";
function App() {
const [count, setCount] = useState(0);
const [number, setNumber] = useState(5);
const result = useMemo(() => {
console.log("Calculating...");
let total = 0;
for (let i = 0; i < 1000000000; i++) {
total += i;
}
return number * 2;
}, [number]);
return (
<div>
<h2>Count: {count}</h2>
<h2>Result: {result}</h2>
<button onClick={() => setCount(count + 1)}>
Increment Count
</button>
<button onClick={() => setNumber(number + 1)}>
Change Number
</button>
</div>
);
}
export default App;- When the component renders initially, the calculation runs.
- When
countchanges, the calculation does not run again. - When
numberchanges, the calculation runs again.
Reason: The dependency array contains [number].
useMemo works based on dependencies.
- During the initial render, React executes the calculation function.
- React stores the calculated value.
- During the next render, React compares the dependencies.
- If dependencies have not changed, React returns the cached value.
- If dependencies have changed, React executes the calculation again and stores the new result.
We can pass multiple dependencies inside the dependency array.
import React, { useMemo, useState } from "react";
function App() {
const [a, setA] = useState(10);
const [b, setB] = useState(20);
const result = useMemo(() => {
console.log("Calculating sum...");
return a + b;
}, [a, b]);
return (
<div>
<h2>Sum: {result}</h2>
<button onClick={() => setA(a + 1)}>
Increase A
</button>
<button onClick={() => setB(b + 1)}>
Increase B
</button>
</div>
);
}
export default App;The calculation runs again whenever either a or b changes.
useMemo is useful when filtering or sorting large arrays.
import React, { useMemo, useState } from "react";
function App() {
const [search, setSearch] = useState("");
const users = [
"John",
"David",
"Alex",
"Peter",
"Smith"
];
const filteredUsers = useMemo(() => {
console.log("Filtering users...");
return users.filter((user) =>
user.toLowerCase().includes(search.toLowerCase())
);
}, [search]);
return (
<div>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search user"
/>
{filteredUsers.map((user) => (
<h3 key={user}>{user}</h3>
))}
</div>
);
}
export default App;- When the search value changes, the filtering operation runs.
- When another unrelated state changes, React can reuse the previous filtered result.
- Avoids unnecessary calculations.
- Improves performance for expensive calculations.
- Stores previously calculated values.
- Helps optimize large applications.
- Useful for filtering and sorting large datasets.
- Adds some memory overhead.
- Adds complexity to the code.
- Not useful for every calculation.
- Can make code harder to understand when overused.
- React may discard the cached value in certain situations.
- useMemo is a React Hook.
- It is used to memoize calculated values.
- It returns a cached value.
- It recalculates when dependencies change.
- It is mainly used for performance optimization.
- It must be called at the top level of a React component or custom Hook.
- Do not call it inside loops, conditions, or nested functions.
- It should not be used for side effects.
- It is a performance optimization, not a guarantee that a calculation will never run again.
| Feature | Purpose |
|---|---|
| useMemo | Memoizes a calculated value |
| useCallback | Memoizes a function reference |
| React.memo | Memoizes a functional component's rendering based on props |
// useMemo
const result = useMemo(() => {
return a + b;
}, [a, b]);
// useCallback
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
// React.memo
const Child = React.memo(ChildComponent);Use useMemo when:
- Performing expensive calculations.
- Filtering large arrays.
- Sorting large datasets.
- Creating derived data from props or state.
- A calculated value is repeatedly needed and profiling shows that recalculation is expensive.
Avoid using useMemo for simple calculations such as:
const sum = a + b;There is no need to use useMemo for every calculation.
Q1. What is useMemo in React?
useMemo is a React Hook used to memoize calculated values and avoid unnecessary recalculations.
Q2. What does useMemo return?
It returns the memoized value.
Q3. When does useMemo execute its calculation again?
When one or more dependencies change, or when React needs to recreate the cached value.
Q4. Can we use useMemo without a dependency array?
No. The dependency array is required. An empty array [] means the calculation is performed during the initial render and the cached value is reused on subsequent renders, subject to React's cache behavior.
Q5. What is the difference between useMemo and useCallback?
useMemo memoizes a calculated value, whereas useCallback memoizes a function reference.
Q6. Does useMemo prevent component re-rendering?
No. It only memoizes a value. The component can still re-render when its state, props, or context changes.
Q7. Can we use useMemo for API calls?
No. useMemo is not designed for side effects or API calls. Use useEffect or an appropriate data-fetching solution.
Q8. Is useMemo always necessary?
No. Use it only when memoization provides a meaningful performance benefit.
useMemo is a React Hook that helps optimize application performance by caching calculated values.
It avoids repeating expensive calculations when the dependencies have not changed.
Remember:
useMemo= Memoize a value.useCallback= Memoize a function.React.memo= Memoize a component.
useCallback is a React Hook used to memoize (cache) a function reference.
It helps prevent unnecessary creation of new function references when a component re-renders.
In simple words:
useCallback remembers a function and returns the same function reference until its dependencies change.
const memoizedFunction = useCallback(() => {
// Function logic
}, [dependencies]);useCallback- React Hook used to memoize a function.() => {}- Function that we want to memoize.dependencies- Values used inside the function that determine when a new function is created.memoizedFunction- Stores the memoized function reference.
function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log("Button clicked");
};
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<Child handleClick={handleClick} />
</div>
);
}
export default Parent;
import React, { useState } from "react";
function Child({ handleClick }) {
console.log("Child component rendered");
return (
<button onClick={handleClick}>
Click Child
</button>
);
}
export default React.memo(Child)Whenever the Parent component re-renders:
- A new
handleClickfunction is created. - The function reference changes.
- The Child receives a new prop.
- The Child component re-renders.
Even though the function logic has not changed, its reference is different.
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<Child handleClick={handleClick} />
</div>
);
}
export default Parent;
import React, { useState, useCallback, memo } from "react";
const Child = ({ handleClick }) => {
console.log("Child component rendered");
return (
<button onClick={handleClick}>
Click Child
</button>
);
};
export default React.memo(Child)- When the Parent component renders initially, the function is created.
- When the count changes, the Parent component re-renders.
- useCallback returns the same function reference because its dependencies have not changed.
- React.memo sees that the Child props have not changed.
- Therefore, the Child component does not need to re-render.
Important: useCallback alone does not prevent a child component from re-rendering. React.memo can help skip rendering when its props remain unchanged.
- During the initial render, React creates the function.
- React stores its reference.
- When the component re-renders, React checks the dependencies.
- If dependencies have not changed, React returns the previous function reference.
- If dependencies have changed, React returns the new function reference.
We can pass dependencies inside the dependency array.
import React, { useState, useCallback } from "react";
function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Current count:", count);
}, [count]);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={handleClick}>
Show Count
</button>
</div>
);
}
export default App;- When count changes, the handleClick function gets a new reference.
- When count does not change, React reuses the previous function reference.
- The function accesses the latest count value after its dependency changes.
We can pass multiple dependencies.
import React, { useState, useCallback } from "react";
function App() {
const [firstName, setFirstName] = useState("John");
const [lastName, setLastName] = useState("David");
const handleUser = useCallback(() => {
console.log(firstName, lastName);
}, [firstName, lastName]);
return (
<div>
<button onClick={handleUser}>
Show User
</button>
<button onClick={() => setFirstName("Alex")}>
Change First Name
</button>
<button onClick={() => setLastName("Smith")}>
Change Last Name
</button>
</div>
);
}
export default App;The function reference changes whenever either firstName or lastName changes.
useCallback can be useful when passing event handlers to memoized child components.
function Parent() {
const [count, setCount] = useState(0);
const handleSubmit = useCallback(() => {
console.log("Form submitted");
}, []);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<Child onSubmit={handleSubmit} />
</div>
);
}
export default Parent;
import React, { useState, useCallback, memo } from "react";
const Child = ({ onSubmit }) => {
console.log("Child rendered");
return (
<button onClick={onSubmit}>
Submit
</button>
);
};
export default React.memo(Child)Here, useCallback keeps the function reference stable when the count changes.
- Prevents unnecessary creation of new function references.
- Helps optimize child components wrapped with React.memo.
- Maintains stable function references between renders.
- Useful when passing callback functions as props.
- Helps optimize dependency-based Hooks and other memoized logic.
- Adds some memory and comparison overhead.
- Makes code more complex.
- Not useful for every function.
- Incorrect dependencies can cause stale values.
- Overusing it can make code harder to maintain.
- useCallback is a React Hook.
- It memoizes a function reference.
- It does not memoize the result of a function.
- It returns a function.
- It checks dependencies using Object.is.
- If dependencies do not change, React returns the previous function reference.
- If dependencies change, React returns a new function reference.
- It is commonly used with React.memo.
- It must be called at the top level of a React component or custom Hook.
- It should not be called inside loops or conditions.
- It is a performance optimization, not a requirement for every function.
| Feature | Purpose |
|---|---|
| useMemo | Memoizes a calculated value |
| useCallback | Memoizes a function reference |
| React.memo | Memoizes component rendering based on props |
// useMemo
const result = useMemo(() => {
return a + b;
}, [a, b]);
// useCallback
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
// React.memo
const Child = React.memo(ChildComponent);- useMemo = Remember a value.
- useCallback = Remember a function.
- React.memo = Remember a component's rendered result.
Use useCallback when:
- Passing functions to child components wrapped with React.memo.
- A function is used as a dependency of useEffect or another Hook.
- A stable function reference is needed for performance optimization.
- Profiling shows unnecessary work caused by changing function references.
Avoid using useCallback for every function because it also has a performance cost.
Q1. What is useCallback in React?
useCallback is a React Hook used to memoize a function reference and prevent unnecessary changes to function references between renders.
Q2. What does useCallback return?
It returns a memoized function reference.
Q3. What is the difference between useMemo and useCallback?
useMemo memoizes a calculated value, whereas useCallback memoizes a function reference.
Q4. Does useCallback prevent component re-rendering?
No. It only helps maintain a stable function reference. React.memo can prevent unnecessary child component rendering when props remain unchanged.
Q5. When does useCallback create a new function reference?
When one or more dependencies change.
Q6. Can we use useCallback without dependencies?
The dependency array is optional. Without it, a new function is returned on every render.
Q7. What happens if we pass an empty dependency array?
React reuses the same function reference between renders, subject to React's cache behavior.
Q8. Can useCallback improve performance?
Yes, when stable function references prevent unnecessary rendering or other expensive work.
Q9. Can useCallback be used with useEffect?
Yes. It can help maintain a stable function dependency for useEffect.
Q10. Is useCallback always necessary?
No. Use it only when it provides a meaningful performance benefit.
useCallback is a React Hook used to memoize function references.
It helps avoid unnecessary changes to function references when a component re-renders.
It is especially useful when passing functions to child components wrapped with React.memo.
- useMemo = Memoize a value.
- useCallback = Memoize a function.
- React.memo = Memoize a component's rendering.
Routing in React JS is used to navigate between different pages or components without reloading the entire webpage.
React uses React Router to implement routing.
For example:
/→ Home Page/about→ About Page/contact→ Contact Page/products→ Products Page
When a user navigates between pages, React displays the corresponding component without refreshing the browser.
createBrowserRouter is a function provided by React Router that is used to create a browser-based routing configuration.
It allows us to define different routes and their corresponding React components.
It uses the browser History API to manage navigation.
Install React Router DOM:
npm install react-router-domimport {
createBrowserRouter,
RouterProvider
} from "react-router-dom";const router = createBrowserRouter([
{
path: "/",
element: <Home />
},
{
path: "/about",
element: <About />
}
]);createBrowserRouter()- Creates the routing configuration.path- Defines the URL path.element- Defines which React component should display.router- Stores the routing configuration.
Home.jsx
function Home() {
return <h1>Welcome to Home Page</h1>;
}
export default Home;About.jsx
function About() {
return <h1>Welcome to About Page</h1>;
}
export default About;Contact.jsx
function Contact() {
return <h1>Welcome to Contact Page</h1>;
}
export default Contact;import {
createBrowserRouter,
RouterProvider
} from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";
const router = createBrowserRouter([
{
path: "/",
element: <Home />
},
{
path: "/about",
element: <About />
},
{
path: "/contact",
element: <Contact />
}
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(
document.getElementById("root")
).render(
<React.StrictMode>
<App />
</React.StrictMode>
);| URL | Component |
|---|---|
/ |
Home |
/about |
About |
/contact |
Contact |
React Router provides the Link component to navigate between routes without reloading the page.
import { Link } from "react-router-dom";
function Home() {
return (
<div>
<h1>Home Page</h1>
<Link to="/about">Go to About</Link>
<br />
<Link to="/contact">Go to Contact</Link>
</div>
);
}
export default Home;Linkis used to navigate between pages.tospecifies the destination URL.- It avoids a full-page reload.
useNavigate is a React Router Hook used for programmatic navigation.
For example, navigating after submitting a form or clicking a button.
import { useNavigate } from "react-router-dom";
function Home() {
const navigate = useNavigate();
return (
<div>
<h1>Home Page</h1>
<button onClick={() => navigate("/about")}>
Go to About
</button>
</div>
);
}
export default Home;useNavigate()returns a navigation function.navigate("/about")navigates to the About page.navigate(-1)navigates to the previous history entry.
Nested routing means defining child routes inside a parent route.
It is useful when multiple pages share the same layout.
import {
createBrowserRouter,
RouterProvider,
Outlet
} from "react-router-dom";
function Layout() {
return (
<div>
<h1>My Website</h1>
<Outlet />
</div>
);
}
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
index: true,
element: <Home />
},
{
path: "about",
element: <About />
}
]
}
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;childrendefines nested routes.Outletdisplays the matching child route.index: truedefines the default child route.- The parent Layout remains visible when navigating between child routes.
/→ Layout + Home/about→ Layout + About
Dynamic routing is used when the URL contains a changing value.
For example:
/user/1/user/2/user/3
We can use dynamic route parameters.
import {
createBrowserRouter,
RouterProvider,
useParams
} from "react-router-dom";
function User() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}
const router = createBrowserRouter([
{
path: "/user/:id",
element: <User />
}
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;:idrepresents a dynamic URL parameter.useParams()accesses the route parameters.- If the URL is
/user/10, the output isUser ID: 10.
errorElement is used to display an error component when a route encounters an error.
import {
createBrowserRouter,
RouterProvider
} from "react-router-dom";
function Home() {
return <h1>Home Page</h1>;
}
function ErrorPage() {
return <h1>Something went wrong!</h1>;
}
const router = createBrowserRouter([
{
path: "/",
element: <Home />,
errorElement: <ErrorPage />
}
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;errorElementdefines the error UI for a route.- It handles errors encountered during route rendering, loading, or actions.
- It can also display a custom error page.
We can create a custom 404 page using a wildcard route.
const router = createBrowserRouter([
{
path: "/",
element: <Home />
},
{
path: "*",
element: <NotFound />
}
]);*matches URLs that do not match other defined routes.NotFounddisplays a custom 404 page.
| Property | Description |
|---|---|
| path | Defines the URL path |
| element | Defines the component to render |
| children | Defines nested routes |
| index | Defines the default child route |
| errorElement | Defines the error UI |
| loader | Loads data before a route renders |
| action | Handles route-related form submissions |
| id | Assigns an ID to a route |
| Name | Purpose |
|---|---|
| createBrowserRouter | Creates browser routing configuration |
| RouterProvider | Provides the router to the application |
| Link | Navigates between routes |
| NavLink | Navigates and provides active-link styling |
| useNavigate | Performs programmatic navigation |
| useParams | Accesses dynamic route parameters |
| useLocation | Accesses current location information |
| useSearchParams | Reads and updates URL query parameters |
| Outlet | Displays nested child routes |
| Link | useNavigate |
|---|---|
| Component | Hook |
| Used for navigation through links | Used for programmatic navigation |
Uses to prop |
Uses navigate() function |
| Useful for menus and navigation bars | Useful after form submission or button actions |
<Link to="/about">About</Link>const navigate = useNavigate();
navigate("/about");- Supports client-side navigation.
- Avoids full-page reloads during navigation.
- Supports nested routing.
- Supports dynamic routes.
- Supports error handling.
- Supports data loading through loaders.
- Supports route actions.
- Makes route configuration organized and maintainable.
createBrowserRoutercreates a routing configuration.RouterProviderconnects the router to the React application.pathdefines the URL.elementdefines the component.Linkis used for navigation.useNavigateis used for programmatic navigation.childrenis used for nested routes.Outletdisplays child routes.useParamsaccesses dynamic route parameters.errorElementdisplays route error UI.*is used for wildcard routes.
Q1. What is routing in React JS?
Routing is used to navigate between different components or pages without reloading the entire webpage.
Q2. What is createBrowserRouter?
It is a React Router function used to create browser-based routing configurations.
Q3. What is RouterProvider?
RouterProvider makes the configured router available to the React application.
Q4. What is the use of Link?
Link is used to navigate between different routes without refreshing the entire page.
Q5. What is useNavigate?
useNavigate is a Hook used for programmatic navigation.
Q6. What is nested routing?
Nested routing means defining child routes inside a parent route.
Q7. What is Outlet?
Outlet is a component used to render the matching child route inside a parent component.
Q8. What is useParams?
useParams is a Hook used to access dynamic parameters from the URL.
Q9. What is errorElement?
errorElement is used to display a custom error UI when a route encounters an error.
Q10. What is the difference between Link and useNavigate?
Link is a component used for navigation through links, whereas useNavigate is a Hook used for programmatic navigation.
Q11. What is an index route?
An index route is the default child route displayed when the parent route matches.
Q12. What is a wildcard route?
A wildcard route uses * to match URLs that do not match other defined routes.
createBrowserRouter is used to configure routing in React applications.
It helps us navigate between different pages without reloading the entire webpage.
createBrowserRouter= Creates routes.RouterProvider= Provides routing.Link= Navigation.useNavigate= Programmatic navigation.children= Nested routes.Outlet= Displays child routes.useParams= Gets URL parameters.errorElement= Handles route errors.
useReducer is a React Hook used to manage state in a React component.
It is an alternative to the useState Hook.
It is especially useful when:
- State management is complex.
- State depends on previous state.
- Multiple actions update the same state.
- We have multiple related state updates.
In simple words:
useReducer manages state using a reducer function and dispatches actions to update the state.
const [state, dispatch] = useReducer(reducer, initialState);useReducer- React Hook used for state management.state- Current state value.dispatch- Function used to send an action.reducer- Function that decides how the state should change.initialState- Initial state value.
A reducer is a function that takes two arguments:
- Current state.
- Action.
It returns the new state.
function reducer(state, action) {
switch (action.type) {
case "ACTION_NAME":
return newState;
default:
return state;
}
}state- Current state.action- Describes what action should happen.action.type- Identifies the action.return- Returns the updated state.
import React, { useReducer } from "react";
// Initial State
const initialState = 0;
// Reducer Function
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
case "RESET":
return 0;
default:
return state;
}
}
function App() {
const [count, dispatch] = useReducer(
reducer,
initialState
);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => dispatch({ type: "INCREMENT" })}>
Increment
</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>
Decrement
</button>
<button onClick={() => dispatch({ type: "RESET" })}>
Reset
</button>
</div>
);
}
export default App;Initially:
Count: 0
When we click Increment:
Count: 1
When we click Decrement:
Count: 0
When we click Reset:
Count: 0
The useReducer Hook works in the following steps:
- Define the initial state.
- Create a reducer function.
- Call useReducer with the reducer and initial state.
- Dispatch an action when the user performs an operation.
- The reducer receives the current state and action.
- The reducer returns the new state.
- React updates the component with the new state.
User clicks button
|
v
dispatch(action)
|
v
Reducer Function
|
v
Current State + Action
|
v
New State Returned
|
v
Component Re-renders
We can manage multiple operations using different action types.
import React, { useReducer } from "react";
const initialState = {
name: "John",
age: 25,
city: "Bangalore"
};
function reducer(state, action) {
switch (action.type) {
case "CHANGE_NAME":
return {
...state,
name: action.payload
};
case "CHANGE_AGE":
return {
...state,
age: action.payload
};
case "CHANGE_CITY":
return {
...state,
city: action.payload
};
default:
return state;
}
}
function App() {
const [user, dispatch] = useReducer(
reducer,
initialState
);
return (
<div>
<h2>Name: {user.name}</h2>
<h2>Age: {user.age}</h2>
<h2>City: {user.city}</h2>
<button
onClick={() =>
dispatch({
type: "CHANGE_NAME",
payload: "David"
})
}
>
Change Name
</button>
<button
onClick={() =>
dispatch({
type: "CHANGE_AGE",
payload: 30
})
}
>
Change Age
</button>
<button
onClick={() =>
dispatch({
type: "CHANGE_CITY",
payload: "Mumbai"
})
}
>
Change City
</button>
</div>
);
}
export default App;Here:
CHANGE_NAMEupdates the name.CHANGE_AGEupdates the age.CHANGE_CITYupdates the city.payloadcontains the value we want to update.- The spread operator (
...state) preserves the other state properties.
dispatch is a function used to send an action to the reducer.
dispatch({
type: "INCREMENT"
});<button
onClick={() =>
dispatch({ type: "INCREMENT" })
}
>
Increment
</button>When dispatch is called:
- An action is sent to the reducer.
- The reducer checks the action type.
- The reducer returns the updated state.
- React renders the component with the new state.
payload is a commonly used property that carries additional data inside an action.
Example:
dispatch({
type: "CHANGE_NAME",
payload: "Alex"
});Inside the reducer:
case "CHANGE_NAME":
return {
...state,
name: action.payload
};Here, "Alex" is the payload value.
Note: payload is a common naming convention, not a mandatory React property.
useReducer can manage multiple form fields.
import React, { useReducer } from "react";
const initialState = {
username: "",
email: "",
password: ""
};
function reducer(state, action) {
return {
...state,
[action.name]: action.value
};
}
function App() {
const [form, dispatch] = useReducer(
reducer,
initialState
);
const handleChange = (e) => {
dispatch({
name: e.target.name,
value: e.target.value
});
};
return (
<div>
<input
name="username"
placeholder="Enter Username"
value={form.username}
onChange={handleChange}
/>
<input
name="email"
placeholder="Enter Email"
value={form.email}
onChange={handleChange}
/>
<input
name="password"
type="password"
placeholder="Enter Password"
value={form.password}
onChange={handleChange}
/>
<h3>{form.username}</h3>
<h3>{form.email}</h3>
</div>
);
}
export default App;- All form fields are managed using one state object.
- The
nameproperty identifies which field should change. - The
valueproperty contains the updated input value. - The reducer updates the corresponding field.
| useState | useReducer |
|---|---|
| Used for simple state management | Useful for complex state management |
| Directly updates state using setter | Updates state using dispatch and reducer |
| Simple to understand | Requires reducer and action logic |
| Suitable for independent state values | Suitable for related state updates |
| Uses a setter function | Uses a dispatch function |
const [count, setCount] = useState(0);
setCount(count + 1);const [count, dispatch] = useReducer(
reducer,
0
);
dispatch({ type: "INCREMENT" });- Makes complex state management organized.
- Keeps state update logic in one place.
- Handles multiple related state updates.
- Makes state transitions easier to understand.
- Useful for forms and complex components.
- Makes reducer logic easier to test.
- More code compared to useState.
- Requires understanding of reducers and actions.
- Can be unnecessary for simple state management.
- Incorrect reducer logic can cause unexpected state updates.
- Large reducers can become difficult to maintain without proper organization.
- useReducer is a React Hook.
- It is an alternative to useState.
- It is useful for complex state management.
- It accepts a reducer function and initial state.
- It returns an array containing state and dispatch.
- The reducer receives state and action.
- The reducer must return the new state.
- dispatch sends an action to the reducer.
- Actions commonly contain a
typeand optionalpayload. - State should not be mutated directly.
- Reducer functions should be pure functions.
- React provides a stable dispatch function reference.
Use useReducer when:
- Managing complex state.
- Handling multiple related state updates.
- Managing forms with many fields.
- State transitions depend on multiple actions.
- You want to keep state update logic separate from UI logic.
Use useState when state management is simple.
Q1. What is useReducer in React?
useReducer is a React Hook used to manage component state. It is an alternative to useState and is useful for complex state logic.
Q2. What are the arguments of useReducer?
It accepts a reducer function and an initial state.
Q3. What does useReducer return?
It returns an array containing the current state and a dispatch function.
Q4. What is a reducer function?
A reducer is a function that takes the current state and an action and returns the new state.
Q5. What is dispatch in useReducer?
dispatch is a function used to send actions to the reducer.
Q6. What is action.type?
action.type identifies which operation should be performed on the state.
Q7. What is payload?
Payload is a commonly used property that carries additional data in an action.
Q8. What is the difference between useState and useReducer?
useState is suitable for simple state management, whereas useReducer is useful for complex state logic involving multiple actions.
Q9. Can we use useReducer with objects?
Yes. useReducer can manage object states and update individual properties using the spread operator.
Q10. Can we use useReducer for form handling?
Yes. It is useful for managing multiple form fields and related form state.
Q11. Should we mutate state directly inside a reducer?
No. We should return a new state instead of directly modifying the existing state.
Q12. Can we use useReducer with Context API?
Yes. We can combine useReducer with Context API to share state and dispatch across multiple components.
useReducer is a React Hook used to manage complex component state.
It manages state using a reducer function and dispatch actions.
It is especially useful when multiple actions need to update related state values.
useState= Simple state management.useReducer= Complex state management.reducer= Contains state update logic.dispatch= Sends an action.action.type= Identifies the operation.payload= Carries additional data.
Redux Toolkit (RTK) is the official recommended way to write Redux logic.
It is a library used for managing global state in React applications.
It makes Redux easier to use by reducing boilerplate code and providing useful functions to manage state.
In simple words:
Redux Toolkit helps us manage and share application state between multiple components without passing props manually.
In React, we can manage state using useState and useReducer.
But when an application becomes large, managing and sharing state between multiple components becomes difficult.
For example:
- Login information
- User details
- Shopping cart
- Product information
- Theme settings
- Notifications
Redux Toolkit helps us manage this shared state in one centralized store.
Redux is a state management library used to manage application state in a predictable way.
It maintains a centralized store where application data is stored.
Redux Toolkit simplifies the process of writing Redux code.
React Component
|
|
useDispatch()
|
v
Action
|
v
Redux Store
|
v
Reducer Logic
|
v
Updated State
|
v
useSelector()
|
v
React Component
First, install Redux Toolkit and React Redux.
npm install @reduxjs/toolkit react-redux@reduxjs/toolkit- Provides functions for creating and managing Redux state.react-redux- Connects Redux with React components.
| Concept | Description |
|---|---|
| Store | Central place where application state is stored |
| Slice | Contains state, reducers, and generated actions |
| Reducer | Defines how state should change |
| Action | Describes what operation should happen |
| Dispatch | Sends an action to the Redux store |
| useSelector | Reads data from the Redux store |
| useDispatch | Returns the dispatch function |
| Provider | Makes the Redux store available to React components |
| configureStore | Creates and configures the Redux store |
| createSlice | Creates a slice with reducers and actions |
A store is a centralized place where the application's global state is stored.
We create a Redux store using configureStore().
import { configureStore } from "@reduxjs/toolkit";
const store = configureStore({
reducer: {}
});
export default store;configureStore()creates the Redux store.reducercontains the reducers used by the application.- The store manages the global application state.
createSlice() is a function provided by Redux Toolkit.
It creates a slice containing:
- Initial state.
- Reducer functions.
- Automatically generated action creators.
const sliceName = createSlice({
name: "sliceName",
initialState: {},
reducers: {
actionName: (state, action) => {
// Update state
}
}
});Create a file called counterSlice.js.
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
count: 0
};
const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.count += 1;
},
decrement: (state) => {
state.count -= 1;
},
reset: (state) => {
state.count = 0;
}
}
});
export const { increment, decrement, reset } =
counterSlice.actions;
export default counterSlice.reducer;namedefines the slice name.initialStatedefines the initial state.reducerscontains state update functions.counterSlice.actionsprovides generated action creators.counterSlice.reducerprovides the reducer function.
Important: Redux Toolkit uses Immer internally, so we can write update logic using mutation-like syntax. Immer creates the immutable state update internally.
configureStore() is used to create the Redux store.
Create a file called store.js.
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";
const store = configureStore({
reducer: {
counter: counterReducer
}
});
export default store;configureStore()creates the store.counteris the key used to access counter state.counterReducerhandles counter state updates.
The state can be accessed using:
state.counter.countProvider is a component provided by React Redux.
It makes the Redux store available to all components inside it.
We need to wrap our React application with Provider.
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Provider store={store}>
<App />
</Provider>
);Providerconnects React with Redux.store={store}passes the Redux store.- All child components can access the Redux state.
useSelector is a Hook provided by React Redux.
It is used to read or access data from the Redux store.
const data = useSelector((state) => state.reducerName);import { useSelector } from "react-redux";
function Counter() {
const count = useSelector(
(state) => state.counter.count
);
return <h2>Count: {count}</h2>;
}
export default Counter;useSelectorreads data from the Redux store.state.counter.countaccesses the count value.- When the selected state changes, the component can re-render.
useDispatch is a Hook provided by React Redux.
It is used to send actions to the Redux store.
const dispatch = useDispatch();
dispatch(actionName());import { useDispatch } from "react-redux";
import { increment } from "./counterSlice";
function Counter() {
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(increment())}>
Increment
</button>
);
}
export default Counter;useDispatch()returns the dispatch function.dispatch()sends an action to Redux.increment()creates an increment action.
Let's create a complete counter application using Redux Toolkit.
src/
|
|-- app/
| |-- store.js
|
|-- features/
| |-- counter/
| |-- counterSlice.js
|
|-- App.jsx
|-- main.jsx
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
count: 0
};
const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.count += 1;
},
decrement: (state) => {
state.count -= 1;
},
reset: (state) => {
state.count = 0;
},
incrementByAmount: (state, action) => {
state.count += action.payload;
}
}
});
export const {
increment,
decrement,
reset,
incrementByAmount
} = counterSlice.actions;
export default counterSlice.reducer;import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "../features/counter/counterSlice";
const store = configureStore({
reducer: {
counter: counterReducer
}
});
export default store;import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./app/store";
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Provider store={store}>
<App />
</Provider>
);import React from "react";
import { useSelector, useDispatch } from "react-redux";
import {
increment,
decrement,
reset,
incrementByAmount
} from "./features/counter/counterSlice";
function App() {
const count = useSelector(
(state) => state.counter.count
);
const dispatch = useDispatch();
return (
<div>
<h1>Redux Toolkit Counter</h1>
<h2>Count: {count}</h2>
<button onClick={() => dispatch(increment())}>
Increment
</button>
<button onClick={() => dispatch(decrement())}>
Decrement
</button>
<button onClick={() => dispatch(reset())}>
Reset
</button>
<button
onClick={() => dispatch(incrementByAmount(5))}
>
Increment By 5
</button>
</div>
);
}
export default App;Initially:
Count: 0
After clicking Increment:
Count: 1
After clicking Decrement:
Count: 0
After clicking Increment By 5:
Count: 5
Payload is used to pass additional data along with an action.
incrementByAmount: (state, action) => {
state.count += action.payload;
}Dispatching an action:
dispatch(incrementByAmount(5));Here:
incrementByAmountis the action creator.5is the payload.action.payloadreceives the value5.- The count increases by 5.
Redux Toolkit follows a unidirectional data flow.
React Component
|
v
useDispatch
|
v
Action
|
v
Reducer
|
v
Redux Store
|
v
useSelector
|
v
React Component
- The user clicks a button.
- The component dispatches an action.
- The reducer receives the action.
- The reducer updates the state.
- Redux stores the updated state.
- useSelector reads the updated state.
- React component re-renders with the new data.
createAsyncThunk is a Redux Toolkit function used to handle asynchronous operations.
For example:
- API calls.
- Fetching user data.
- Loading products.
- Submitting form data.
import { createAsyncThunk } from "@reduxjs/toolkit";
export const fetchUsers = createAsyncThunk(
"users/fetchUsers",
async () => {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
return await response.json();
}
);createAsyncThunk automatically generates three action types:
| Action | Description |
|---|---|
| pending | API request is in progress |
| fulfilled | API request completed successfully |
| rejected | API request failed |
These actions can be handled inside extraReducers.
- Reduces boilerplate code.
- Makes Redux easier to understand.
- Provides centralized state management.
- Uses Immer for immutable state updates.
- Supports asynchronous operations.
- Provides built-in Redux DevTools integration.
- Makes application state easier to maintain.
- Supports scalable application architecture.
- Adds extra setup compared to simple useState.
- Requires understanding of Redux concepts.
- Can be unnecessary for small applications.
- Adds dependencies to the project.
- Requires proper organization when the application becomes large.
| Feature | useState | useReducer | Redux Toolkit |
|---|---|---|---|
| State management | Local | Local | Global |
| Complexity | Simple | Medium | Suitable for larger state management |
| Data sharing | Through props or Context | Through props or Context | Shared through store |
| Best for | Simple state | Complex local state | Shared application state |
| Setup | Easy | Moderate | Requires store and Provider |
Use Redux Toolkit when:
- Multiple components need the same state.
- Application has complex global state.
- Managing shopping cart data.
- Managing authentication information.
- Managing shared user information.
- Handling API-related application state.
- Passing props through many component levels becomes difficult.
Avoid using Redux Toolkit for every small state value.
For simple local state, useState is usually sufficient.
- Redux Toolkit is the official recommended approach for writing Redux logic.
- It is used for centralized state management.
- configureStore creates the Redux store.
- createSlice creates a slice containing reducers and actions.
- Provider makes the store available to React components.
- useSelector reads data from the Redux store.
- useDispatch dispatches actions.
- createAsyncThunk handles asynchronous logic.
- action.payload carries additional data.
- extraReducers handles actions generated outside the slice's reducers.
- Redux follows unidirectional data flow.
- Redux Toolkit uses Immer for immutable state updates.
Q1. What is Redux Toolkit?
Redux Toolkit is the official recommended way to write Redux logic. It simplifies global state management in React applications.
Q2. Why do we use Redux Toolkit?
We use Redux Toolkit to manage shared application state and reduce unnecessary boilerplate code.
Q3. What is a Redux store?
A Redux store is a centralized place where application state is stored.
Q4. What is createSlice?
createSlice is a Redux Toolkit function that creates a slice containing initial state, reducers, and automatically generated action creators.
Q5. What is configureStore?
configureStore is used to create and configure the Redux store.
Q6. What is useSelector?
useSelector is a React Redux Hook used to read data from the Redux store.
Q7. What is useDispatch?
useDispatch is a React Redux Hook used to dispatch actions to the Redux store.
Q8. What is Provider?
Provider is a React Redux component that makes the Redux store available to the application.
Q9. What is payload?
Payload is additional data passed along with an action.
Q10. What is createAsyncThunk?
createAsyncThunk is used to handle asynchronous operations such as API requests.
Q11. What are pending, fulfilled and rejected?
They are the three action states generated by createAsyncThunk to represent the progress and result of an asynchronous operation.
Q12. What is the difference between Redux and Redux Toolkit?
Redux is the state management library, whereas Redux Toolkit is the recommended approach for writing Redux logic with less boilerplate.
Q13. Can we mutate state in Redux Toolkit?
We can write mutation-like update syntax inside Redux Toolkit reducers because it uses Immer internally to produce immutable state updates.
Q14. Can we use Redux Toolkit without React?
Yes. Redux Toolkit can be used with JavaScript applications without React. React Redux is needed to connect it with React components.
Redux Toolkit is a powerful state management solution for React applications.
It helps manage global state in a centralized and organized way.
It makes Redux easier by reducing boilerplate code and providing useful functions.
- configureStore = Creates the store.
- createSlice = Creates reducers and actions.
- Provider = Connects the store to React.
- useSelector = Reads state.
- useDispatch = Sends actions.
- createAsyncThunk = Handles asynchronous operations.
- payload = Passes additional data.
- extraReducers = Handles external actions.