• Follow Us On :
ReactJS Interview Questions

150+ Essential ReactJS Interview Questions: Master Your Next Interview

Preparing for a React developer position requires mastering comprehensive ReactJS interview questions that span fundamental concepts, advanced patterns, performance optimization, and real-world problem-solving. Whether you’re a junior developer facing your first React interview or an experienced engineer preparing for senior-level positions, understanding the most common ReactJS interview questions and their nuanced answers proves essential for success.

This exhaustive guide compiles over 150 ReactJS interview questions organized by difficulty level and topic area, including React fundamentals, components and props, state management, hooks, lifecycle methods, performance optimization, Redux, testing, and advanced patterns. Each question includes detailed explanations, code examples where relevant, and insights into what interviewers seek in responses. Mastering these ReactJS interview questions prepares you to confidently discuss React architecture, demonstrate problem-solving abilities, and showcase your development expertise.

The ReactJS interview questions presented here reflect current industry practices and the latest React features including hooks, concurrent mode, and modern patterns that have transformed React development. From explaining virtual DOM to implementing custom hooks, from optimizing component rendering to architecting scalable applications, this comprehensive resource covers everything you need to excel in your React interview.

Fundamental ReactJS Interview Questions

1. What is React and Why Use It?

Answer: React is a JavaScript library developed by Facebook for building user interfaces, particularly single-page applications where you need a fast, interactive user experience. React allows developers to create reusable UI components that manage their own state and compose them to build complex interfaces.

Key reasons to use React:

  • Component-based architecture promotes reusability and maintainability
  • Virtual DOM provides excellent performance through efficient updates
  • Declarative syntax makes code more predictable and easier to debug
  • Strong ecosystem with extensive tools, libraries, and community support
  • React Native enables mobile development using the same concepts
  • Backed by Facebook ensuring long-term support and continuous improvements

2. What is JSX and Why Do We Use It?

Answer: JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML-like code in JavaScript files. JSX makes React code more readable and expressive by resembling the final UI structure.

jsx
// JSX example
const element = <h1 className="greeting">Hello, World!</h1>;

// Equivalent JavaScript
const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, World!'
);

JSX benefits:

  • Provides visual structure matching UI output
  • Allows embedding JavaScript expressions using curly braces
  • Prevents injection attacks through automatic escaping
  • Catches errors at compile time
  • Improves developer experience with familiar HTML-like syntax

3. Explain Virtual DOM and How It Works

Answer: The Virtual DOM is a lightweight JavaScript representation of the actual DOM. React maintains a virtual copy of the DOM tree in memory and uses it to optimize updates through a process called reconciliation.

Virtual DOM workflow:

  1. When state changes, React creates a new Virtual DOM tree
  2. React compares the new Virtual DOM with the previous snapshot (diffing)
  3. React calculates the minimum number of changes needed
  4. React updates only the changed elements in the real DOM (reconciliation)

Benefits:

  • Minimizes expensive DOM manipulations
  • Batches multiple updates for efficiency
  • Provides cross-browser compatibility
  • Enables declarative UI programming

4. What is the Difference Between State and Props?

Answer:

Props (Properties):

  • Read-only data passed from parent to child components
  • Cannot be modified by the receiving component
  • Used to pass data down the component tree
  • Cause re-renders when changed by parent
jsx
// Parent passing props
<ChildComponent name="John" age={30} />

// Child receiving props
function ChildComponent({ name, age }) {
  return <div>{name} is {age} years old</div>;
}

State:

  • Mutable data managed within a component
  • Can be changed using setState or useState
  • Private to the component
  • Causes component re-render when updated
jsx
const [count, setCount] = useState(0);
setCount(count + 1); // Updates state

5. What are React Components? Explain Functional vs Class Components

Answer: Components are independent, reusable pieces of UI that return React elements describing what should appear on screen.

Functional Components:

jsx
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// Arrow function syntax
const Welcome = ({ name }) => <h1>Hello, {name}</h1>;

Class Components:

jsx
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Modern trend: Functional components with Hooks are now preferred as they’re simpler, easier to test, and provide better code reusability.

6. What is the Significance of Keys in React?

Answer: Keys help React identify which items in a list have changed, been added, or removed. Keys should be unique among siblings and stable across re-renders.

jsx
const items = ['Apple', 'Banana', 'Orange'];

// Good - using unique IDs
items.map(item => <li key={item.id}>{item.name}</li>)

// Bad - using array index (can cause bugs)
items.map((item, index) => <li key={index}>{item}</li>)

Why keys matter:

  • Optimize rendering performance
  • Maintain component state correctly
  • Prevent unnecessary re-renders
  • Ensure predictable component behavior

7. What is ReactDOM and How is it Different from React?

Answer: React and ReactDOM are separate packages serving different purposes:

React: Core library for creating components and managing their logic ReactDOM: Provides DOM-specific methods for rendering React components to the browser

jsx
import React from 'react';
import ReactDOM from 'react-dom/client';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

This separation allows React to target different platforms (web via ReactDOM, mobile via React Native, VR via React VR, etc.).

8. What are Controlled vs Uncontrolled Components?

Answer:

Controlled Components: Form elements whose values are controlled by React state

jsx
function ControlledInput() {
  const [value, setValue] = useState('');
  
  return (
    <input 
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />
  );
}

Uncontrolled Components: Form elements that maintain their own internal state

jsx
function UncontrolledInput() {
  const inputRef = useRef();
  
  const handleSubmit = () => {
    alert(inputRef.current.value);
  };
  
  return <input ref={inputRef} />;
}

Controlled components are preferred as they provide single source of truth and easier validation.

9. What is Props Drilling and How to Avoid It?

Answer: Props drilling occurs when you pass data through multiple nested components to reach a deeply nested child component.

Problem:

jsx
<GrandParent data={data}>
  <Parent data={data}>
    <Child data={data}>
      <GrandChild data={data} />
    </Child>
  </Parent>
</GrandParent>

Solutions:

  • Context API for global state
  • Component composition restructuring
  • State management libraries (Redux, Zustand)
  • Custom hooks for shared logic

10. Explain React Fragments and Why Use Them

Answer: Fragments let you group multiple children without adding extra nodes to the DOM.

jsx
// Using Fragment
function List() {
  return (
    <React.Fragment>
      <li>Item 1</li>
      <li>Item 2</li>
    </React.Fragment>
  );
}

// Short syntax
function List() {
  return (
    <>
      <li>Item 1</li>
      <li>Item 2</li>
    </>
  );
}

Benefits:

  • Avoids unnecessary wrapper divs
  • Keeps DOM clean
  • Better semantic HTML
  • Slightly better performance

ReactJS Hooks Interview Questions

11. What are React Hooks and Why Were They Introduced?

Answer: Hooks are functions that let you “hook into” React state and lifecycle features from functional components. Introduced in React 16.8 to solve several problems:

Problems hooks solved:

  • Difficult to reuse stateful logic between components
  • Complex components became hard to understand
  • Classes confused both people and machines
  • Wrapper hell from HOCs and render props

Common built-in hooks:

  • useState – State management
  • useEffect – Side effects
  • useContext – Context consumption
  • useReducer – Complex state logic
  • useCallback – Memoized callbacks
  • useMemo – Memoized values
  • useRef – Persistent references

12. Explain useState Hook with Examples

Answer: useState adds state to functional components.

jsx
import { useState } from 'react';

function Counter() {
  // Declare state variable
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

// Multiple state variables
function Form() {
  const [name, setName] = useState('');
  const [age, setAge] = useState(0);
  const [email, setEmail] = useState('');
}

// Object state
function User() {
  const [user, setUser] = useState({
    name: '',
    email: ''
  });
  
  // Update object state
  setUser(prev => ({...prev, name: 'John'}));
}

Key points:

  • Returns array with current state and updater function
  • Initial state passed as argument
  • State updates trigger re-renders
  • Use functional updates for state depending on previous state

13. How Does useEffect Hook Work?

Answer: useEffect performs side effects in functional components, replacing lifecycle methods from class components.

jsx
import { useEffect } from 'react';

// Runs after every render
useEffect(() => {
  console.log('Component rendered');
});

// Runs once on mount (empty dependency array)
useEffect(() => {
  console.log('Component mounted');
}, []);

// Runs when dependencies change
useEffect(() => {
  console.log('Count changed:', count);
}, [count]);

// Cleanup function
useEffect(() => {
  const subscription = subscribeToData();
  
  return () => {
    subscription.unsubscribe();
  };
}, []);

UseEffect phases:

  1. Component renders
  2. DOM updates
  3. Effect callback executes
  4. Cleanup from previous effect (if exists)

14. What is useContext Hook and When to Use It?

Answer: useContext consumes context values without wrapping components in Context.Consumer.

jsx
import { createContext, useContext } from 'react';

// Create context
const ThemeContext = createContext('light');

// Provider
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

// Consumer using useContext
function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Button</button>;
}

Use cases:

  • Global app configuration (theme, language)
  • User authentication state
  • Avoiding props drilling
  • Sharing data across component tree

15. Explain useReducer Hook

Answer: useReducer manages complex state logic with multiple sub-values or when next state depends on previous state.

jsx
import { useReducer } from 'react';

// Reducer function
function counterReducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'reset':
      return { count: 0 };
    default:
      throw new Error('Unknown action');
  }
}

function Counter() {
  const [state, dispatch] = useReducer(
    counterReducer, 
    { count: 0 }
  );
  
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({type: 'increment'})}>
        +
      </button>
      <button onClick={() => dispatch({type: 'decrement'})}>
        -
      </button>
    </div>
  );
}

useReducer vs useState:

  • useReducer for complex state logic
  • useReducer for multiple sub-values
  • useState for simple state

16. What are useCallback and useMemo Hooks?

Answer: Both hooks optimize performance by memoizing values.

useCallback – Memoizes callback functions:

jsx
import { useCallback } from 'react';

function Parent() {
  const [count, setCount] = useState(0);
  
  // Memoized callback
  const handleClick = useCallback(() => {
    setCount(c => c + 1);
  }, []); // Empty deps - function never changes
  
  return <Child onClick={handleClick} />;
}

useMemo – Memoizes computed values:

jsx
import { useMemo } from 'react';

function ExpensiveComponent({ data }) {
  // Only recalculates when data changes
  const expensiveValue = useMemo(() => {
    return data.reduce((acc, item) => acc + item.value, 0);
  }, [data]);
  
  return <div>{expensiveValue}</div>;
}

When to use:

  • Prevent unnecessary re-renders of child components
  • Optimize expensive calculations
  • Maintain referential equality

17. Explain use Ref Hook and Its Use Cases

Answer: useRef creates a mutable reference that persists across renders without causing re-renders.

jsx
import { useRef, useEffect } from 'react';

function TextInput() {
  const inputRef = useRef(null);
  
  useEffect(() => {
    // Access DOM element
    inputRef.current.focus();
  }, []);
  
  return <input ref={inputRef} />;
}

// Storing previous values
function Counter() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef();
  
  useEffect(() => {
    prevCountRef.current = count;
  });
  
  const prevCount = prevCountRef.current;
  
  return <div>Now: {count}, Before: {prevCount}</div>;
}

// Storing mutable values without re-renders
function Timer() {
  const intervalRef = useRef();
  
  const startTimer = () => {
    intervalRef.current = setInterval(() => {
      console.log('Tick');
    }, 1000);
  };
  
  const stopTimer = () => {
    clearInterval(intervalRef.current);
  };
}

Common use cases:

  • Accessing DOM elements
  • Storing previous values
  • Holding mutable values
  • Interval/timeout IDs

18. What are Custom Hooks?

Answer: Custom hooks are JavaScript functions that use React hooks and enable reusable stateful logic across components.

jsx
// Custom hook for fetching data
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err);
        setLoading(false);
      });
  }, [url]);
  
  return { data, loading, error };
}

// Usage
function UserProfile() {
  const { data, loading, error } = useFetch('/api/user');
  
  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  
  return <div>{data.name}</div>;
}

// Custom hook for form handling
function useForm(initialValues) {
  const [values, setValues] = useState(initialValues);
  
  const handleChange = (e) => {
    setValues({
      ...values,
      [e.target.name]: e.target.value
    });
  };
  
  const reset = () => setValues(initialValues);
  
  return { values, handleChange, reset };
}

Custom hook rules:

  • Must start with “use”
  • Can call other hooks
  • Promote code reusability
  • Share stateful logic
Also Read: ReactJS Tutorial

19. Explain use Layout Effect vs use Effect

Answer: Both hooks are similar but differ in execution timing.

useEffect:

  • Runs asynchronously after render
  • Doesn’t block browser painting
  • Used for most side effects

useLayoutEffect:

  • Runs synchronously after DOM mutations
  • Blocks browser painting
  • Used when you need to read layout and synchronously re-render
jsx
import { useEffect, useLayoutEffect } from 'react';

function Component() {
  // Runs after paint
  useEffect(() => {
    console.log('useEffect runs');
  });
  
  // Runs before paint
  useLayoutEffect(() => {
    console.log('useLayoutEffect runs first');
  });
}

When to use useLayoutEffect:

  • Measuring DOM elements
  • Preventing visual flicker
  • Synchronous DOM updates

20. What is use Imperative Handle Hook?

Answer: useImperativeHandle customizes the instance value exposed to parent components when using ref.

jsx
import { useImperativeHandle, forwardRef, useRef } from 'react';

const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef();
  
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
    clear: () => {
      inputRef.current.value = '';
    }
  }));
  
  return <input ref={inputRef} />;
});

// Parent component
function Parent() {
  const inputRef = useRef();
  
  return (
    <div>
      <CustomInput ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>
        Focus
      </button>
      <button onClick={() => inputRef.current.clear()}>
        Clear
      </button>
    </div>
  );
}

Advanced ReactJS Interview Questions

21. Explain React Lifecycle Methods (Class Components)

Answer: Lifecycle methods allow you to run code at specific times in a component’s life.

Mounting phase:

  • constructor() – Initialize state
  • static getDerivedStateFromProps() – Sync state with props
  • render() – Return JSX
  • componentDidMount() – Run side effects

Updating phase:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate() – Optimize rendering
  • render()
  • getSnapshotBeforeUpdate() – Capture DOM info
  • componentDidUpdate() – Run side effects after update

Unmounting phase:

  • componentWillUnmount() – Cleanup

Error handling:

  • static getDerivedStateFromError()
  • componentDidCatch()

Hooks equivalents:

  • componentDidMount → useEffect(() => {}, [])
  • componentDidUpdate → useEffect(() => {})
  • componentWillUnmount → useEffect cleanup

22. What is React Fiber Architecture?

Answer: React Fiber is the reimplementation of React’s core algorithm introduced in React 16. It enables:

Key features:

  • Incremental rendering – Split work into chunks
  • Pause, abort, or reuse work – Better responsiveness
  • Priority-based rendering – Different priorities for updates
  • Concurrent features – Multiple versions of UI in memory

Benefits:

  • Smoother animations
  • Better perceived performance
  • Responsive during expensive operations
  • Foundation for Suspense and Concurrent Mode

23. Explain React Suspense and Lazy Loading

Answer: Suspense lets components “wait” for something before rendering, commonly used with code-splitting.

jsx
import { lazy, Suspense } from 'react';

// Lazy load component
const HeavyComponent = lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <HeavyComponent />
    </Suspense>
  );
}

// Data fetching with Suspense (experimental)
function ProfilePage() {
  return (
    <Suspense fallback={<h1>Loading profile...</h1>}>
      <ProfileDetails />
      <Suspense fallback={<h2>Loading posts...</h2>}>
        <ProfileTimeline />
      </Suspense>
    </Suspense>
  );
}

Benefits:

  • Code splitting
  • Improved initial load time
  • Better user experience
  • Declarative loading states

24. What are Higher-Order Components (HOCs)?

Answer: HOCs are functions that take a component and return a new enhanced component.

jsx
// HOC that adds loading functionality
function withLoading(Component) {
  return function WithLoadingComponent({ isLoading, ...props }) {
    if (isLoading) return <div>Loading...</div>;
    return <Component {...props} />;
  };
}

// Usage
const UserListWithLoading = withLoading(UserList);

// HOC for authentication
function withAuth(Component) {
  return function AuthComponent(props) {
    const { isAuthenticated } = useAuth();
    
    if (!isAuthenticated) {
      return <Redirect to="/login" />;
    }
    
    return <Component {...props} />;
  };
}

Use cases:

  • Code reuse
  • Props manipulation
  • State abstraction
  • Render hijacking

Modern alternative: Custom hooks often preferred

25. Explain Render Props Pattern

Answer: Render props is a technique for sharing code between components using a prop whose value is a function.

jsx
// Component with render prop
class Mouse extends React.Component {
  state = { x: 0, y: 0 };
  
  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  };
  
  render() {
    return (
      <div onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

// Usage
<Mouse render={({ x, y }) => (
  <h1>Mouse position: {x}, {y}</h1>
)} />

// Children as function variant
<Mouse>
  {({ x, y }) => (
    <h1>Mouse position: {x}, {y}</h1>
  )}
</Mouse>

Modern alternative: Custom hooks provide cleaner solution

26. What is React Context API and When to Use It?

Answer: Context provides a way to share values between components without explicitly passing props through every level.

jsx
import { createContext, useContext, useState } from 'react';

// Create context
const ThemeContext = createContext();

// Provider component
function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  
  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  };
  
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// Custom hook for consuming context
function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

// Usage
function ThemedButton() {
  const { theme, toggleTheme } = useTheme();
  return (
    <button 
      onClick={toggleTheme}
      className={theme}
    >
      Toggle Theme
    </button>
  );
}

When to use Context:

  • Global app state (theme, locale, auth)
  • Avoid props drilling
  • Share data across many components

When not to use:

  • Frequently changing data (performance issues)
  • Simple parent-child communication

27. How Does React Handle Performance Optimization?

Answer: React provides several techniques for performance optimization:

1. React.memo – Prevents unnecessary re-renders:

jsx
const MemoizedComponent = React.memo(Component, (prevProps, nextProps) => {
  // Return true if props are equal (skip render)
  return prevProps.id === nextProps.id;
});

2. useMemo – Memoize expensive calculations:

jsx
const expensiveValue = useMemo(() => {
  return computeExpensiveValue(a, b);
}, [a, b]);

3. useCallback – Memoize functions:

jsx
const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

4. Code splitting with lazy loading:

jsx
const OtherComponent = React.lazy(() => import('./OtherComponent'));

5. Virtualization for long lists (react-window, react-virtualized)

6. Key prop for efficient list updates

7. shouldComponentUpdate in class components

28. What is Redux and How Does it Work with React?

Answer: Redux is a predictable state container for JavaScript apps, commonly used with React for global state management.

Core concepts:

  • Store – Single source of truth
  • Actions – Events describing what happened
  • Reducers – Pure functions specifying state changes
  • Dispatch – Sends actions to store
jsx
// Redux setup
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';

// Reducer
function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// Store
const store = createStore(counterReducer);

// App with Provider
<Provider store={store}>
  <App />
</Provider>

// Component using Redux
function Counter() {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>
        +
      </button>
    </div>
  );
}

Modern alternatives: Redux Toolkit, Zustand, Jotai, Recoil

29. Explain Error Boundaries in React

Answer: Error boundaries are React components that catch JavaScript errors in their child component tree, log errors, and display fallback UI.

jsx
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  componentDidCatch(error, errorInfo) {
    // Log error to service
    console.error('Error caught:', error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    
    return this.props.children;
  }
}

// Usage
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

Error boundaries catch:

  • Errors during rendering
  • Lifecycle methods
  • Constructors

Error boundaries DON’T catch:

  • Event handlers
  • Asynchronous code
  • Server-side rendering
  • Errors in error boundary itself

30. What is Reconciliation in React?

Answer: Reconciliation is the algorithm React uses to diff one tree with another to determine which parts need to be changed.

Diffing algorithm:

  1. Different element types – Destroy old tree, build new tree
  2. Same element types – Keep DOM node, update changed attributes
  3. Component elements – Update props, call render
  4. Keys in lists – Match children across renders

Optimization strategies:

  • Breadth-first search
  • Component-level diffing
  • Batch updates
  • Priority-based scheduling

Performance considerations:

  • Keys help identify moved elements
  • Type changes cause full rebuilds
  • shouldComponentUpdate prevents unnecessary work

React Performance and Best Practices Questions

31. How to Optimize React Application Performance?

Answer: Multiple strategies improve React performance:

1. Code splitting and lazy loading:

jsx
const Dashboard = lazy(() => import('./Dashboard'));

2. Memoization:

jsx
const MemoComponent = React.memo(MyComponent);
const memoValue = useMemo(() => compute(a, b), [a, b]);
const memoCallback = useCallback(() => doSomething(), []);

3. Virtualize long lists:

jsx
import { FixedSizeList } from 'react-window';

<FixedSizeList
  height={600}
  itemCount={1000}
  itemSize={35}
>
  {Row}
</FixedSizeList>

4. Optimize images:

  • Lazy loading images
  • Use appropriate formats (WebP)
  • Responsive images
  • Image CDN

5. Debouncing and throttling:

jsx
const debouncedSearch = useMemo(
  () => debounce(handleSearch, 300),
  []
);

6. Use production build 7. Avoid inline functions in JSX 8. Use fragments instead of divs 9. Optimize bundle size 10. Use React DevTools Profiler

32. What are Common React Anti-Patterns to Avoid?

Answer:

1. Mutating state directly:

jsx
// Bad
state.items.push(newItem);

// Good
setItems([...items, newItem]);

2. Using index as key:

jsx
// Bad
items.map((item, index) => <li key={index}>{item}</li>)

// Good
items.map(item => <li key={item.id}>{item}</li>)

3. Not cleaning up effects:

jsx
// Bad
useEffect(() => {
  const subscription = subscribe();
  // No cleanup
}, []);

// Good
useEffect(() => {
  const subscription = subscribe();
  return () => subscription.unsubscribe();
}, []);

4. Copying props to state:

jsx
// Bad - derived state
const [value, setValue] = useState(props.value);

// Good - use props directly or memo
const value = props.value;

5. Inline object/array in dependencies:

jsx
// Bad - new object every render
useEffect(() => {}, [{ id: 1 }]);

// Good
useEffect(() => {}, [id]);

33. How to Handle Forms in React?

Answer:

Controlled components (recommended):

jsx
function Form() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: ''
  });
  
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev

Leave a Reply

Your email address will not be published. Required fields are marked *