Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Props in React JS

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.

Types of props in React

  1. strings
  2. Number
  3. Boolean
  4. arrays
  5. object
  6. function
  7. children
  8. jsx/ component

Default Props

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.

What happens when a prop is missing, undefined, or null?

-----Guest ----Guest -----Amit ------Nothing visible --------Empty string

Why does null not use the default?

Because JavaScript default parameters apply only when the value is undefined, not when it is null, an empty string, false, or 0.

Why do we use default props?

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.

Important rules about props

  1. Props are read-only. A child component should not directly modify the props it receives.

  2. Props flow from parent to child. To communicate changes back to a parent, a child can call a function passed as a prop.

  3. Props can have default values. For example, function Welcome({ name = "Guest" }).

  4. Props can be any JavaScript value, including strings, numbers, objects, arrays, functions, and JSX elements.

  5. Props are different from state. Props are passed into a component; state is data managed by a component and can change over time.

What is JSX?

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.

JSX Rules

  1. Return a single enclosing element
  2. Close all tags
  3. Use camelCase for many attributes
  4. class and for attributes are changed to className and htmlFor.
  5. use JSX Expression to access js inside JSX

JSX Expression Rules

  1. we can't declare a variable inside the jsx expression
  2. we can initialization | re-initialization inside
  3. we can't use conditional statements. Only ternary operator
  4. we can't use loops . only map we can use.
  5. we can execute the js expressions inside the jsx Expression

Conditional Rendering in React.js

  1. 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

2. Why Do We Need Conditional Rendering?

Conditional rendering is useful when an application needs to display different content depending on the current situation.

Common use cases include:

  1. Showing login or logout buttons.
  2. Displaying different content for authenticated and unauthenticated users.
  3. Showing loading indicators while fetching data.
  4. Displaying error messages when something goes wrong.
  5. Showing success messages after submitting a form.
  6. Displaying products based on availability.
  7. Showing or hiding a modal, dropdown, or menu.
  8. Rendering different components based on user roles.
  9. Displaying a message when a list is empty.
  10. Showing validation errors when form inputs are invalid.

3. Different Ways to Perform Conditional Rendering

React supports several ways to conditionally render elements. The most common methods are:

Method Best use case

  1. if...else Multiple statements or complex conditions
  2. Ternary operator (? :) Choosing between two UI elements
  3. Logical AND (&&) Rendering something only when a condition is true
  4. Logical OR (||) Providing a fallback value
  5. switch statement Choosing among multiple alternatives

Interview Questions and Answers

Q1. What is conditional rendering in React?

Conditional rendering is the process of displaying different UI elements or components based on conditions, using JavaScript expressions and statements.

Q2. Which operators are commonly used for conditional rendering?

The most common operators are the ternary operator (? :), logical AND (&&), and logical OR (||). React components can also use if...else and switch statements.

Q3. What is the difference between && and the ternary operator?

&& 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.

Q4. Can we use if...else inside JSX?

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.

Q5. What happens when a condition in && is false?

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.

Q6. Can we conditionally render components?

Yes. For example:

jsx {isLoggedIn ? : }

Q7. Can conditional rendering work with state?

Yes. When state changes, React renders the component again and evaluates the conditional expressions using the updated state.

Q8. What is the difference between conditional rendering and CSS hiding?

Conditional rendering can omit an element from the rendered DOM. CSS hiding generally keeps the element mounted but makes it invisible.

Q9. Can we use multiple conditions?

Yes. You can combine conditions with logical operators, use ternary expressions, or use if...else and switch statements.

Q10. Why should we avoid deeply nested ternary operators?

They make code harder to read, debug, and maintain. For complicated conditions, use early returns, if...else, or helper functions.

What is nullish coalescing operator ?

The nullish coalescing operator (??) returns the right-hand side operand only when the left-hand side operand is strictly null or undefined.

React useState Hook

1. Definition

  • useState is 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.
  • useState was introduced in React 16.8.

2. Syntax

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.

3. Example

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;

4. Most Important Points

  1. useState is a React Hook.
  2. It is used to manage state in functional components.
  3. It returns an array containing two values:
    • The current state.
    • A function to update the state.
  4. The initial state is provided as an argument to useState().
  5. Updating state schedules a re-render of the component.
  6. Never update state directly; use its setter function.
  7. State updates may be batched by React.
  8. State updates are not guaranteed to be immediately reflected in the current render.
  9. State can store numbers, strings, booleans, arrays, objects, and other values.
  10. Each call to useState manages a separate state variable.
  11. Hooks must be called at the top level of a React component or custom Hook.
  12. Do not call Hooks inside loops, conditions, or nested functions.
  13. The initial value is used when the component initializes, not on every re-render.
  14. React compares the next state with the current state using Object.is.
  15. When updating objects or arrays, create a new object or array instead of mutating the existing state.

5. Updating State

Direct Update

const [count, setCount] = useState(0);

setCount(10);

Update Using Previous State

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.

6. State with Different Data Types

Number

const [age, setAge] = useState(25);

String

const [name, setName] = useState("John");

Boolean

const [isVisible, setIsVisible] = useState(true);

Array

const [items, setItems] = useState([]);

Object

const [user, setUser] = useState({
  name: "John",
  age: 25
});

7. Updating Objects and Arrays

Updating an Object

setUser((prevUser) => ({
  ...prevUser,
  age: 26
}));

Updating an Array

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.

8. Lazy Initialization

  • 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.

9. Common Mistakes

  • 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 useState inside conditions, loops, or nested functions.
  • Using Hooks outside a function component or custom Hook.
  • Forgetting to import useState when needed.

10. Difference Between State and Normal Variables

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

11. When to Use useState

  • 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.

12. Quick Revision

  • Definition: useState manages 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 useState only at the top level of a component or custom Hook.

React useRef Hook

1. Definition

  • useRef is 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.
  • useRef returns an object containing a current property.

2. Syntax

const ref = useRef(initialValue);
  • useRef - React Hook used to create a ref object.
  • initialValue - The initial value assigned to ref.current.
  • ref - The returned ref object.
  • ref.current - The property used to read or update the stored value.

3. Example: Accessing a DOM Element

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;

Explanation

  1. useRef(null) creates a ref object.
  2. The ref attribute connects the ref to the input element.
  3. React assigns the input DOM element to inputRef.current after the element is mounted.
  4. When the button is clicked, inputRef.current.focus() focuses the input field.
  5. Updating or using the ref does not itself trigger a re-render.

4. Most Important Points

  1. useRef is a React Hook.
  2. It can store mutable values between renders.
  3. It returns an object with a current property.
  4. The initial value is passed as an argument to useRef().
  5. Updating ref.current does not trigger a re-render.
  6. The same ref object is retained across renders of the component.
  7. It can be used to access DOM elements.
  8. It can store values such as timer IDs, previous values, and mutable counters.
  9. It should be called at the top level of a function component or custom Hook.
  10. Changing ref.current does not automatically update the UI.
  11. Do not use refs as a replacement for state when a value needs to be displayed and updated in the UI.
  12. In React Strict Mode, components may render more than once in development; avoid relying on a particular ref object created during a discarded render.
  13. Read or write refs in event handlers and effects rather than during rendering, except for predictable initialization patterns.

5. Example: Storing a Value Without Re-rendering

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;

Explanation

  • 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 useState instead if the UI must update immediately when the value changes.

6. Common Uses of useRef

  • Accessing DOM elements.
  • Focusing an input field.
  • Playing or pausing media through DOM methods.
  • Storing timer IDs returned by setTimeout or setInterval.
  • Keeping mutable values between renders.
  • Storing previous values for comparison.
  • Integrating with third-party libraries that require DOM references.

7. Difference Between useRef and useState

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

8. Difference Between useRef and createRef

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

9. Common Mistakes

  • Expecting a ref update to trigger a re-render.
  • Using useRef instead of useState for 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.current always contains a DOM element; it may initially be null.

10. Quick Revision

  • Definition: useRef stores 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 useState when a change must update the UI.
  • Use useRef when a value must persist but changing it should not itself update the UI.

Props Drilling in React JS

1. Definition

  • 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."

2. Example of Props 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;

Explanation

  • App creates the username data.
  • App passes username to Parent.
  • Parent passes it to Child.
  • Child passes it to GrandChild.
  • GrandChild uses the data to display the username.

Important: Parent and Child only pass the prop; they do not use it themselves. This is props drilling.

3. Most Important Points

  1. Props drilling means passing props through multiple levels of components.
  2. Props are used to share data between React components.
  3. The data usually flows from parent components to child components.
  4. Intermediate components may pass props without using them.
  5. Props drilling can make code harder to maintain as an application grows.
  6. It can make components more tightly coupled to the data they pass through.
  7. Props drilling is not always bad; for a small component tree, it can be simple and appropriate.
  8. React Context can help avoid passing the same props through many intermediate components.
  9. State management libraries such as Redux or Zustand can help manage shared state in larger applications.
  10. Component composition can sometimes eliminate the need for props drilling.

4. Problems with 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.

5. How to Avoid Props Drilling

Method 1: React Context API

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.
  • Provider makes a value available to descendant components.
  • useContext() reads the nearest matching context value.
  • Intermediate components no longer need to pass the username prop.

Method 2: State Management Libraries

  • Redux
  • Zustand
  • MobX

These libraries can help manage shared state across many components when the application requires it.

Method 3: Component Composition

  • Pass components or JSX as children or other props.
  • This can reduce the need for intermediate components to know about specific data.

6. Props Drilling vs Context API

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

7. When Should You Avoid Props Drilling?

  • 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.

8. Quick Revision

  • 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 in React JS

1. What is React.memo?

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.

2. Syntax

const MemoizedComponent = React.memo(Component);

Or:

import React, { memo } from "react";

const MemoizedComponent = memo(Component);

3. Example Without React.memo

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.

4. Example With React.memo

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.

5. How React.memo Works

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.

6. Example With Parent and Child

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)

Output

When the button is clicked:

  • Parent component re-renders.
  • Count value increases.
  • Child component does not re-render because its name prop is unchanged.

9. Advantages of React.memo

  1. Prevents unnecessary component re-renders.
  2. Improves performance in suitable cases.
  3. Useful for components that render frequently.
  4. Helps optimize large React applications.
  5. Reduces unnecessary rendering work.

10. Disadvantages of React.memo

  1. Adds a small comparison overhead.
  2. Not useful for every component.
  3. Can make code more complex.
  4. Does not prevent re-renders caused by a component's own state changes.
  5. Does not prevent re-renders caused by consumed context changes.

11. Important Points to Remember

  • 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.

12. Difference Between React.memo, useMemo and useCallback

Feature Purpose
React.memo Memoizes a component
useMemo Memoizes a calculated value
useCallback Memoizes a function reference

Example

// React.memo
const Child = React.memo(ChildComponent);

// useMemo
const result = useMemo(() => {
  return a + b;
}, [a, b]);

// useCallback
const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);

13. When Should We Use React.memo?

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.

14. Interview Questions

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.


Conclusion

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 Hook in React JS

1. What is useMemo?

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.

2. Syntax

const memoizedValue = useMemo(() => {
  return calculation;
}, [dependencies]);

Syntax Explanation

  • useMemo - React Hook used for memoization.
  • () => {} - Function containing the calculation.
  • dependencies - Values that determine when recalculation is required.
  • memoizedValue - Stores the calculated result.

3. Example Without useMemo

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;

Problem

Whenever the component re-renders, the expensive calculation runs again, even if number has not changed.

4. Example With useMemo

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;

Output Explanation

  • When the component renders initially, the calculation runs.
  • When count changes, the calculation does not run again.
  • When number changes, the calculation runs again.

Reason: The dependency array contains [number].

5. How useMemo Works

useMemo works based on dependencies.

  1. During the initial render, React executes the calculation function.
  2. React stores the calculated value.
  3. During the next render, React compares the dependencies.
  4. If dependencies have not changed, React returns the cached value.
  5. If dependencies have changed, React executes the calculation again and stores the new result.

6. useMemo With Multiple Dependencies

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.

7. useMemo With Array Filtering

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;

Explanation

  • When the search value changes, the filtering operation runs.
  • When another unrelated state changes, React can reuse the previous filtered result.

8. Advantages of useMemo

  1. Avoids unnecessary calculations.
  2. Improves performance for expensive calculations.
  3. Stores previously calculated values.
  4. Helps optimize large applications.
  5. Useful for filtering and sorting large datasets.

9. Disadvantages of useMemo

  1. Adds some memory overhead.
  2. Adds complexity to the code.
  3. Not useful for every calculation.
  4. Can make code harder to understand when overused.
  5. React may discard the cached value in certain situations.

10. Important Points to Remember

  • 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.

11. Difference Between useMemo, useCallback and React.memo

Feature Purpose
useMemo Memoizes a calculated value
useCallback Memoizes a function reference
React.memo Memoizes a functional component's rendering based on props

Examples

// useMemo
const result = useMemo(() => {
  return a + b;
}, [a, b]);

// useCallback
const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);

// React.memo
const Child = React.memo(ChildComponent);

12. When Should We Use useMemo?

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.

13. Interview Questions

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.


14. Conclusion

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 Hook in React JS

1. What is useCallback?

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.

2. Syntax

const memoizedFunction = useCallback(() => {
  // Function logic
}, [dependencies]);

Syntax Explanation

  • 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.

3. Example Without useCallback

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)

Problem

Whenever the Parent component re-renders:

  1. A new handleClick function is created.
  2. The function reference changes.
  3. The Child receives a new prop.
  4. The Child component re-renders.

Even though the function logic has not changed, its reference is different.

4. Example With useCallback

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)

Output Explanation

  • 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.

5. How useCallback Works

  1. During the initial render, React creates the function.
  2. React stores its reference.
  3. When the component re-renders, React checks the dependencies.
  4. If dependencies have not changed, React returns the previous function reference.
  5. If dependencies have changed, React returns the new function reference.

6. useCallback With Dependencies

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;

Explanation

  • 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.

7. useCallback With Multiple Dependencies

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.

8. useCallback With API or Event Handler Functions

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.

9. Advantages of useCallback

  1. Prevents unnecessary creation of new function references.
  2. Helps optimize child components wrapped with React.memo.
  3. Maintains stable function references between renders.
  4. Useful when passing callback functions as props.
  5. Helps optimize dependency-based Hooks and other memoized logic.

10. Disadvantages of useCallback

  1. Adds some memory and comparison overhead.
  2. Makes code more complex.
  3. Not useful for every function.
  4. Incorrect dependencies can cause stale values.
  5. Overusing it can make code harder to maintain.

11. Important Points to Remember

  • 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.

12. Difference Between useMemo, useCallback and React.memo

Feature Purpose
useMemo Memoizes a calculated value
useCallback Memoizes a function reference
React.memo Memoizes component rendering based on props

Examples

// useMemo
const result = useMemo(() => {
  return a + b;
}, [a, b]);

// useCallback
const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);

// React.memo
const Child = React.memo(ChildComponent);

Easy Way to Remember

  • useMemo = Remember a value.
  • useCallback = Remember a function.
  • React.memo = Remember a component's rendered result.

13. When Should We Use useCallback?

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.

14. Interview Questions

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.


15. Conclusion

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.

Remember

  • useMemo = Memoize a value.
  • useCallback = Memoize a function.
  • React.memo = Memoize a component's rendering.

Routing in React JS (createBrowserRouter)

1. What is Routing in React JS?

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.

2. What is createBrowserRouter?

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.

Installation

Install React Router DOM:

npm install react-router-dom

Import

import {
  createBrowserRouter,
  RouterProvider
} from "react-router-dom";

3. Basic Syntax of createBrowserRouter

const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />
  },
  {
    path: "/about",
    element: <About />
  }
]);

Explanation

  • createBrowserRouter() - Creates the routing configuration.
  • path - Defines the URL path.
  • element - Defines which React component should display.
  • router - Stores the routing configuration.

4. Basic Example of createBrowserRouter

Step 1: Create Components

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;

Step 2: Configure Routes in App.jsx

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;

Step 3: Render App in main.jsx

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>
);

Output

URL Component
/ Home
/about About
/contact Contact

5. Navigation Using Link

React Router provides the Link component to navigate between routes without reloading the page.

Example

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;

Important

  • Link is used to navigate between pages.
  • to specifies the destination URL.
  • It avoids a full-page reload.

6. Navigation Using useNavigate

useNavigate is a React Router Hook used for programmatic navigation.

For example, navigating after submitting a form or clicking a button.

Example

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;

Important

  • useNavigate() returns a navigation function.
  • navigate("/about") navigates to the About page.
  • navigate(-1) navigates to the previous history entry.

7. Nested Routing Using createBrowserRouter

Nested routing means defining child routes inside a parent route.

It is useful when multiple pages share the same layout.

Example

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;

Explanation

  • children defines nested routes.
  • Outlet displays the matching child route.
  • index: true defines the default child route.
  • The parent Layout remains visible when navigating between child routes.

Output

  • / → Layout + Home
  • /about → Layout + About

8. Dynamic Routing Using createBrowserRouter

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.

Example

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;

Explanation

  • :id represents a dynamic URL parameter.
  • useParams() accesses the route parameters.
  • If the URL is /user/10, the output is User ID: 10.

9. Error Page Using errorElement

errorElement is used to display an error component when a route encounters an error.

Example

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;

Explanation

  • errorElement defines the error UI for a route.
  • It handles errors encountered during route rendering, loading, or actions.
  • It can also display a custom error page.

10. Not Found Page Using path: "*"

We can create a custom 404 page using a wildcard route.

Example

const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />
  },
  {
    path: "*",
    element: <NotFound />
  }
]);

Explanation

  • * matches URLs that do not match other defined routes.
  • NotFound displays a custom 404 page.

11. Important Properties of createBrowserRouter

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

12. Important React Router Hooks and Components

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

13. Difference Between Link and useNavigate

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 Example

<Link to="/about">About</Link>

useNavigate Example

const navigate = useNavigate();

navigate("/about");

14. Advantages of createBrowserRouter

  1. Supports client-side navigation.
  2. Avoids full-page reloads during navigation.
  3. Supports nested routing.
  4. Supports dynamic routes.
  5. Supports error handling.
  6. Supports data loading through loaders.
  7. Supports route actions.
  8. Makes route configuration organized and maintainable.

15. Important Points to Remember

  • createBrowserRouter creates a routing configuration.
  • RouterProvider connects the router to the React application.
  • path defines the URL.
  • element defines the component.
  • Link is used for navigation.
  • useNavigate is used for programmatic navigation.
  • children is used for nested routes.
  • Outlet displays child routes.
  • useParams accesses dynamic route parameters.
  • errorElement displays route error UI.
  • * is used for wildcard routes.

16. Interview Questions

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.


17. Conclusion

createBrowserRouter is used to configure routing in React applications.

It helps us navigate between different pages without reloading the entire webpage.

Remember

  • 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 Hook in React JS

1. What is useReducer?

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.

2. Syntax

const [state, dispatch] = useReducer(reducer, initialState);

Syntax Explanation

  • 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.

3. What is a Reducer Function?

A reducer is a function that takes two arguments:

  1. Current state.
  2. Action.

It returns the new state.

Syntax

function reducer(state, action) {
  switch (action.type) {
    case "ACTION_NAME":
      return newState;

    default:
      return state;
  }
}

Explanation

  • state - Current state.
  • action - Describes what action should happen.
  • action.type - Identifies the action.
  • return - Returns the updated state.

4. Basic Example of useReducer (Counter)

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;

Output Explanation

Initially:

Count: 0

When we click Increment:

Count: 1

When we click Decrement:

Count: 0

When we click Reset:

Count: 0

5. How useReducer Works

The useReducer Hook works in the following steps:

  1. Define the initial state.
  2. Create a reducer function.
  3. Call useReducer with the reducer and initial state.
  4. Dispatch an action when the user performs an operation.
  5. The reducer receives the current state and action.
  6. The reducer returns the new state.
  7. React updates the component with the new state.

Flow

User clicks button
       |
       v
dispatch(action)
       |
       v
Reducer Function
       |
       v
Current State + Action
       |
       v
New State Returned
       |
       v
Component Re-renders

6. useReducer With Multiple Actions

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;

Explanation

Here:

  • CHANGE_NAME updates the name.
  • CHANGE_AGE updates the age.
  • CHANGE_CITY updates the city.
  • payload contains the value we want to update.
  • The spread operator (...state) preserves the other state properties.

7. What is dispatch in useReducer?

dispatch is a function used to send an action to the reducer.

Syntax

dispatch({
  type: "INCREMENT"
});

Example

<button
  onClick={() =>
    dispatch({ type: "INCREMENT" })
  }
>
  Increment
</button>

When dispatch is called:

  1. An action is sent to the reducer.
  2. The reducer checks the action type.
  3. The reducer returns the updated state.
  4. React renders the component with the new state.

8. What is action.payload?

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.

9. useReducer With Form Handling

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;

Explanation

  • All form fields are managed using one state object.
  • The name property identifies which field should change.
  • The value property contains the updated input value.
  • The reducer updates the corresponding field.

10. Difference Between useState and useReducer

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

useState Example

const [count, setCount] = useState(0);

setCount(count + 1);

useReducer Example

const [count, dispatch] = useReducer(
  reducer,
  0
);

dispatch({ type: "INCREMENT" });

11. Advantages of useReducer

  1. Makes complex state management organized.
  2. Keeps state update logic in one place.
  3. Handles multiple related state updates.
  4. Makes state transitions easier to understand.
  5. Useful for forms and complex components.
  6. Makes reducer logic easier to test.

12. Disadvantages of useReducer

  1. More code compared to useState.
  2. Requires understanding of reducers and actions.
  3. Can be unnecessary for simple state management.
  4. Incorrect reducer logic can cause unexpected state updates.
  5. Large reducers can become difficult to maintain without proper organization.

13. Important Points to Remember

  • 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 type and optional payload.
  • State should not be mutated directly.
  • Reducer functions should be pure functions.
  • React provides a stable dispatch function reference.

14. When Should We Use useReducer?

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.

15. Interview Questions

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.


16. Conclusion

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.

Remember

  • 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) in React JS

1. What is Redux Toolkit?

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.

2. Why Do We Need Redux Toolkit?

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.

3. What is Redux?

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.

Redux Toolkit Architecture

        React Component
               |
               |
          useDispatch()
               |
               v
            Action
               |
               v
          Redux Store
               |
               v
          Reducer Logic
               |
               v
          Updated State
               |
               v
          useSelector()
               |
               v
        React Component

4. Installation of Redux Toolkit

First, install Redux Toolkit and React Redux.

npm install @reduxjs/toolkit react-redux

Packages Explanation

  • @reduxjs/toolkit - Provides functions for creating and managing Redux state.
  • react-redux - Connects Redux with React components.

5. Important Concepts in Redux Toolkit

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

6. What is Store?

A store is a centralized place where the application's global state is stored.

We create a Redux store using configureStore().

Example

import { configureStore } from "@reduxjs/toolkit";

const store = configureStore({
  reducer: {}
});

export default store;

Explanation

  • configureStore() creates the Redux store.
  • reducer contains the reducers used by the application.
  • The store manages the global application state.

7. What is createSlice?

createSlice() is a function provided by Redux Toolkit.

It creates a slice containing:

  1. Initial state.
  2. Reducer functions.
  3. Automatically generated action creators.

Syntax

const sliceName = createSlice({
  name: "sliceName",
  initialState: {},
  reducers: {
    actionName: (state, action) => {
      // Update state
    }
  }
});

Example

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;

Explanation

  • name defines the slice name.
  • initialState defines the initial state.
  • reducers contains state update functions.
  • counterSlice.actions provides generated action creators.
  • counterSlice.reducer provides 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.

8. What is configureStore?

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;

Explanation

  • configureStore() creates the store.
  • counter is the key used to access counter state.
  • counterReducer handles counter state updates.

The state can be accessed using:

state.counter.count

9. What is Provider?

Provider 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.

Example: main.jsx

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>
);

Explanation

  • Provider connects React with Redux.
  • store={store} passes the Redux store.
  • All child components can access the Redux state.

10. What is useSelector?

useSelector is a Hook provided by React Redux.

It is used to read or access data from the Redux store.

Syntax

const data = useSelector((state) => state.reducerName);

Example

import { useSelector } from "react-redux";

function Counter() {
  const count = useSelector(
    (state) => state.counter.count
  );

  return <h2>Count: {count}</h2>;
}

export default Counter;

Explanation

  • useSelector reads data from the Redux store.
  • state.counter.count accesses the count value.
  • When the selected state changes, the component can re-render.

11. What is useDispatch?

useDispatch is a Hook provided by React Redux.

It is used to send actions to the Redux store.

Syntax

const dispatch = useDispatch();

dispatch(actionName());

Example

import { useDispatch } from "react-redux";
import { increment } from "./counterSlice";

function Counter() {
  const dispatch = useDispatch();

  return (
    <button onClick={() => dispatch(increment())}>
      Increment
    </button>
  );
}

export default Counter;

Explanation

  • useDispatch() returns the dispatch function.
  • dispatch() sends an action to Redux.
  • increment() creates an increment action.

12. Complete Redux Toolkit Counter Example

Let's create a complete counter application using Redux Toolkit.

Folder Structure

src/
|
|-- app/
|    |-- store.js
|
|-- features/
|    |-- counter/
|         |-- counterSlice.js
|
|-- App.jsx
|-- main.jsx

Step 1: Create 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;
    },

    incrementByAmount: (state, action) => {
      state.count += action.payload;
    }
  }
});

export const {
  increment,
  decrement,
  reset,
  incrementByAmount
} = counterSlice.actions;

export default counterSlice.reducer;

Step 2: Create store.js

import { configureStore } from "@reduxjs/toolkit";

import counterReducer from "../features/counter/counterSlice";

const store = configureStore({
  reducer: {
    counter: counterReducer
  }
});

export default store;

Step 3: Create main.jsx

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>
);

Step 4: Create App.jsx

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;

Output

Initially:

Count: 0

After clicking Increment:

Count: 1

After clicking Decrement:

Count: 0

After clicking Increment By 5:

Count: 5

13. What is Action Payload?

Payload is used to pass additional data along with an action.

Example

incrementByAmount: (state, action) => {
  state.count += action.payload;
}

Dispatching an action:

dispatch(incrementByAmount(5));

Here:

  • incrementByAmount is the action creator.
  • 5 is the payload.
  • action.payload receives the value 5.
  • The count increases by 5.

14. Redux Toolkit Data Flow

Redux Toolkit follows a unidirectional data flow.

       React Component
              |
              v
         useDispatch
              |
              v
          Action
              |
              v
          Reducer
              |
              v
         Redux Store
              |
              v
         useSelector
              |
              v
       React Component

Step-by-Step Explanation

  1. The user clicks a button.
  2. The component dispatches an action.
  3. The reducer receives the action.
  4. The reducer updates the state.
  5. Redux stores the updated state.
  6. useSelector reads the updated state.
  7. React component re-renders with the new data.

15. What is createAsyncThunk?

createAsyncThunk is a Redux Toolkit function used to handle asynchronous operations.

For example:

  • API calls.
  • Fetching user data.
  • Loading products.
  • Submitting form data.

Syntax

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();
  }
);

Explanation

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.

16. Advantages of Redux Toolkit

  1. Reduces boilerplate code.
  2. Makes Redux easier to understand.
  3. Provides centralized state management.
  4. Uses Immer for immutable state updates.
  5. Supports asynchronous operations.
  6. Provides built-in Redux DevTools integration.
  7. Makes application state easier to maintain.
  8. Supports scalable application architecture.

17. Disadvantages of Redux Toolkit

  1. Adds extra setup compared to simple useState.
  2. Requires understanding of Redux concepts.
  3. Can be unnecessary for small applications.
  4. Adds dependencies to the project.
  5. Requires proper organization when the application becomes large.

18. Difference Between useState, useReducer and Redux Toolkit

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

19. When Should We Use Redux Toolkit?

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.

20. Important Points to Remember

  • 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.

21. Interview Questions

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.


22. Conclusion

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.

Remember

  • 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.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages