Reactjs Interview Questions

For Beginners To Experts


Reactjs Interview Questions

1. What is React?

React is a JavaScript library developed by Facebook for building user interfaces, especially single-page applications where data changes over time without reloading the page.

2. What are the main features of React?

  • Declarative UI
  • Component-based architecture
  • Virtual DOM for efficient rendering
  • One-way data binding
  • Supports server-side rendering
  • Uses JSX syntax

3. What is JSX?

JSX stands for JavaScript XML. It allows writing HTML elements directly within JavaScript code. It makes writing and understanding React components easier.

4. What is the difference between a component and an element in React?

A React component is a function or class that returns a piece of UI (JSX). A React element is an object representation of a UI node created by calling a component.

5. What are functional components?

Functional components are React components written as JavaScript functions. They return JSX and can use hooks like useState and useEffect.

6. What are class components?

Class components are React components defined using ES6 classes. They extend React.Component and have access to lifecycle methods and this.state.

7. What is the virtual DOM?

The virtual DOM is a lightweight in-memory representation of the real DOM. React uses it to detect changes and update the actual DOM efficiently.

8. How does React use the virtual DOM to improve performance?

React compares the new virtual DOM with the previous one using a diffing algorithm. It updates only the parts of the real DOM that changed, improving performance.

9. What are props in React?

Props (short for properties) are inputs passed to components from parent components. They are read-only and used to pass data and event handlers.

10. What is state in React?

State is a built-in object used to store dynamic data in a component. Unlike props, state is managed within the component and can change over time.

11. How do you update state in a React component?

In class components, you use this.setState(). In functional components, you use the setState function returned by the useState hook.

12. What is the difference between props and state?

  • Props: Passed from parent to child, read-only.
  • State: Managed within the component, can be updated.

13. What are default props?

Default props are fallback values provided to a component in case no props are passed. They can be set using Component.defaultProps.

14. What is prop drilling?

Prop drilling refers to passing props through multiple levels of nested components, even if intermediate components do not use them, just to reach a deep child.

15. How do you handle events in React?

React uses camelCase syntax for event handlers (e.g., onClick) and passes a synthetic event object to the handler function.

16. What is the useState hook?

useState is a hook that lets functional components have state. It returns an array with the current state and a function to update it.

17. What is the useEffect hook?

useEffect lets you run side effects like fetching data, setting up subscriptions, or updating the DOM after render in a functional component.

18. What are side effects in React?

Side effects are operations that interact with the outside world (e.g., API calls, timers, modifying DOM) and don't belong in the main rendering logic.

19. When does useEffect run?

By default, useEffect runs after every render. You can control when it runs by passing a dependency array as the second argument.

20. What is conditional rendering in React?

Conditional rendering allows you to render different UI elements or components based on conditions (e.g., using if, ternary operators, or &&).

21. How do you apply CSS in React?

  1. Use inline styles: <div style={{ color: 'red' }}>
  2. Import CSS files: import './App.css' and use class names.

22. What is lifting state up?

  1. Moving shared state to the closest common parent component.
  2. This allows multiple children to access and modify the shared state.

23. How do you handle forms in React?

  1. Controlled components: inputs tied to state with onChange.
  2. Use useState or form libraries like Formik.

24. What is a key in React lists?

  1. A unique identifier used to optimize list rendering.
  2. Helps React identify which items changed, added, or removed.

25. Why shouldn’t you use array indexes as keys?

  1. They can cause issues when the list is reordered or changed.
  2. It can lead to incorrect DOM updates and bugs.

26. What are fragments in React?

  1. Fragments let you group elements without adding extra DOM nodes.
  2. Use <></> or <React.Fragment>.

27. How do you conditionally render components?

  1. Use ternary operators: {isLoggedIn ? <Dashboard /> : <Login />}
  2. Use logical AND: {show && <Modal />}

28. What is context in React?

  1. Context provides a way to pass data without prop drilling.
  2. It uses React.createContext, Provider, and useContext.

29. What is useContext?

  1. A hook to consume context values in functional components.
  2. Replaces the need for Context.Consumer.

30. How do you optimize performance in React?

  1. Use React.memo, useMemo, and useCallback.
  2. Split code using lazy loading and reduce unnecessary re-renders.

31. What is React.memo?

  1. A higher-order component that memoizes functional components.
  2. Prevents re-render if props haven't changed.

32. What is useMemo?

  1. A hook that memoizes expensive calculations.
  2. Only recalculates when dependencies change.

33. What is useCallback?

  1. A hook that memoizes functions to avoid recreation on every render.
  2. Helps prevent unnecessary re-renders in child components.

34. What is lazy loading in React?

  1. Loading components only when needed using React.lazy.
  2. Reduces initial load time by splitting code.

35. What is suspense in React?

  1. A component to handle fallback content while lazy components load.
  2. Used with React.lazy to show a loader or placeholder.

36. What are higher-order components (HOCs)?

  1. Functions that take a component and return a new enhanced component.
  2. Used for reusing logic like authentication, theming, etc.

37. What is reconciliation in React?

  1. The process of comparing virtual DOM trees to determine changes.
  2. Efficiently updates the real DOM with minimal operations.

38. What are controlled and uncontrolled components?

  1. Controlled: form inputs managed by React state.
  2. Uncontrolled: inputs use the DOM to manage their own state via refs.

39. What is the role of refs in React?

  1. Refs provide a way to directly access DOM nodes or React elements.
  2. Useful for focus, text selection, animations, or integrating third-party libraries.

40. What is the difference between useEffect and useLayoutEffect?

  1. useEffect runs after the DOM is painted.
  2. useLayoutEffect runs synchronously before painting, blocking render.

41. What is the difference between state and props?

  1. Props are read-only and passed from parent to child.
  2. State is managed within the component and can be updated internally.

42. What is prop drilling?

  1. Passing props through multiple nested components to reach a deep child.
  2. Can be avoided using Context API or state management libraries.

43. How to avoid prop drilling?

  1. Use React Context API to share state across components.
  2. Use state management tools like Redux or Zustand.

44. What is a PureComponent?

  1. A component that implements shouldComponentUpdate with a shallow prop and state comparison.
  2. Used to prevent unnecessary re-renders for performance optimization.

45. How do you handle errors in React?

  1. Use error boundaries by creating a class component with componentDidCatch.
  2. Use try/catch inside event handlers or async logic.

46. What is useReducer?

  1. A hook used for more complex state logic, similar to Redux.
  2. Provides state and dispatch method to update state via actions.

47. What is the difference between useEffect and useRef?

  1. useEffect runs side effects like API calls.
  2. useRef stores mutable values without causing re-renders.

48. What are render props?

  1. A technique where a component's child is a function that returns JSX.
  2. Used for sharing logic between components without HOCs.

49. What is a virtual DOM?

  1. An in-memory representation of the actual DOM.
  2. Improves performance by reducing direct DOM manipulations.

50. What is server-side rendering (SSR)?

  1. Rendering components on the server before sending to the browser.
  2. Improves SEO and performance by serving pre-rendered HTML.

51. What is hydration in React?

  1. The process of attaching event listeners to static content rendered on the server.
  2. Makes a server-rendered page interactive in the browser.

52. What is a controlled component?

  1. A form input element whose value is controlled by React state.
  2. State updates on every input change via onChange.

53. What is an uncontrolled component?

  1. A form input element that manages its own state internally via the DOM.
  2. Use ref to access its value when needed.

54. How to fetch data in React?

  1. Use useEffect with fetch or axios to get data on mount.
  2. Use React Query or SWR for advanced data fetching and caching.

55. What is the use of keys in lists?

  1. Keys help React identify and track list items across renders.
  2. Prevents unnecessary re-renders and maintains element state.

56. What is reconciliation algorithm?

  1. React’s diffing algorithm that compares virtual DOM trees to detect changes.
  2. Efficiently updates only the necessary parts of the real DOM.

57. What are portals in React?

  1. Allows rendering a component outside the main DOM hierarchy.
  2. Used for modals, tooltips, or floating elements.

58. What are default props?

  1. Default values assigned to props if none are provided.
  2. Can be set via Component.defaultProps or default parameters.

59. What is the use of useImperativeHandle?

  1. Customizes the instance value exposed to parent components using refs.
  2. Used with forwardRef for controlled ref exposure.

60. What is React DevTools?

  1. A browser extension to inspect the React component tree.
  2. Helps debug props, state, hooks, and performance.

61. What is memoization in React?

  1. Memoization caches the result of expensive function calls.
  2. In React, React.memo prevents unnecessary re-renders of functional components.

62. What is the useCallback hook?

  1. useCallback returns a memoized version of a callback function.
  2. It prevents re-creation of functions on each render, improving performance.

63. What is the useMemo hook?

  1. useMemo returns a memoized value based on dependencies.
  2. Useful for avoiding expensive calculations on every render.

64. How is context different from Redux?

  1. Context is built-in and good for small apps or themes.
  2. Redux is more powerful, scalable, and has middleware support.

65. What is lazy loading in React?

  1. It allows components to load only when needed.
  2. Implemented using React.lazy and Suspense.

66. What is code splitting?

  1. Dividing code into smaller bundles to load on demand.
  2. Improves performance by reducing initial bundle size.

67. What is a higher-order function vs higher-order component?

  1. A higher-order function takes a function and returns a new one.
  2. A higher-order component takes a component and returns a new one with added props or behavior.

68. What is a Fragment in React?

  1. A Fragment lets you group multiple elements without adding extra DOM nodes.
  2. Written as <React.Fragment> or shorthand <>.

69. Can we return multiple elements from a component?

  1. Yes, using arrays or Fragments.
  2. Each child must have a unique key if using arrays.

70. What is reconciliation?

  1. It’s the process React uses to update the DOM efficiently.
  2. Compares new virtual DOM with the previous one and updates changed parts only.

71. What are synthetic events?

  1. React’s cross-browser wrapper around native events.
  2. Provides consistent behavior across browsers.

72. How do you update state based on previous state?

  1. Use a callback in setState: setCount(prev => prev + 1).
  2. Ensures the correct previous value is used, especially in async updates.

73. What is StrictMode in React?

  1. A tool for highlighting potential issues in an application.
  2. Does not render UI but runs checks in development mode.

74. What are keys in React?

  1. Special string attributes used to track items in lists.
  2. Should be unique and stable to prevent rendering issues.

75. Why shouldn't we update state directly?

  1. Direct updates don't trigger re-rendering.
  2. Can lead to inconsistent UI and bugs.

76. How do you share logic between components?

  1. Using custom hooks for function components.
  2. Using higher-order components or render props.

77. What is the useLayoutEffect hook?

  1. Fires synchronously after DOM mutations but before painting.
  2. Used when you need to measure layout or DOM before browser paints.

78. What’s the difference between useEffect and useLayoutEffect?

  1. useEffect runs after the paint, useLayoutEffect before the paint.
  2. useLayoutEffect can block visual updates if misused.

79. What are the rules of hooks?

  1. Only call hooks at the top level, not inside loops or conditions.
  2. Only call hooks from React functions or custom hooks.

80. How can you optimize performance in React?

  1. Use memoization (React.memo, useMemo, useCallback).
  2. Code splitting, lazy loading, and avoiding unnecessary renders.

81. What is a ref?

  1. A reference to access DOM nodes or React elements directly.
  2. Created using useRef or createRef.

82. Can React work without JSX?

  1. Yes, JSX is syntactic sugar for React.createElement().
  2. JSX is optional but more readable and concise.

83. What is event delegation in React?

  1. React uses a single event listener at the root to handle all events.
  2. Improves performance and memory usage.

84. What is forwardRef?

  1. Allows passing a ref through a component to a child DOM element.
  2. Used for reusable components that expose internal nodes.

85. What is a callback ref?

  1. A ref created using a callback function instead of useRef.
  2. Gives more control over when and how the ref is set.

86. What are portals used for?

  1. Render children into a DOM node outside the parent hierarchy.
  2. Useful for modals, popovers, and overlays.

87. What is React Query?

  1. A data-fetching library for managing remote server state in React.
  2. Handles caching, background updates, and synchronization.

88. What is SWR?

  1. A React hook for data fetching by Vercel, built on the stale-while-revalidate strategy.
  2. Optimized for caching and background revalidation.

89. What is the difference between component and element?

  1. A component is a class or function definition.
  2. An element is what gets returned from a component and rendered to the DOM.

90. What is the purpose of dangerouslySetInnerHTML?

  1. Used to inject raw HTML into a component.
  2. Should be used cautiously to avoid XSS attacks.

React Coding Interview Questions

1. Create a simple functional component

import React from 'react';

function Greeting() {
  return <h1>Hello, World!</h1>;
}
  

2. Create a component with props

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

3. Use useState to manage a counter

import React, { useState } from 'react';

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

4. Create a controlled input

function InputExample() {
  const [text, setText] = useState('');
  return (
    <input value={text} onChange={e => setText(e.target.value)} />
  );
}
  

5. Pass functions as props

function Button({ handleClick }) {
  return <button onClick={handleClick}>Click Me</button>;
}
  

6. useEffect to fetch data

useEffect(() => {
  fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(data => setData(data));
}, []);
  

7. Conditional rendering

function Status({ isLoggedIn }) {
  return isLoggedIn ? <p>Welcome!</p> : <p>Please log in.</p>;
}
  

8. Mapping an array to components

function List({ items }) {
  return (
    <ul>
      {items.map(item => <li key={item.id}>{item.name}</li>)}
    </ul>
  );
}
  

9. Creating a custom hook

function useToggle(initial) {
  const [state, setState] = useState(initial);
  const toggle = () => setState(prev => !prev);
  return [state, toggle];
}
  

10. Using useRef

const inputRef = useRef();

function focusInput() {
  inputRef.current.focus();
}
  

11. Forwarding refs

const Input = React.forwardRef((props, ref) => (
  <input ref={ref} {...props} />
));
  

12. Lazy loading components

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

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

13. Memoizing components

const MemoizedComponent = React.memo(function Component({ value }) {
  return <p>{value}</p>;
});
  

14. Styling with inline styles

const style = { color: 'blue', fontSize: '20px' };
return <h1 style={style}>Styled Text</h1>;
  

15. Handling form submission

function Form() {
  const handleSubmit = (e) => {
    e.preventDefault();
    alert('Form submitted!');
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}
  

16. Using useContext

const ThemeContext = React.createContext();

function ThemedComponent() {
  const theme = useContext(ThemeContext);
  return <p>Theme is {theme}</p>;
}
  

17. Error boundaries

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
  

18. Fragment usage

return (
  <>
    <h1>Title</h1>
    <p>Paragraph</p>
  </>
);
  

19. useReducer for state management

const reducer = (state, action) => {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    default: return state;
  }
};

const [state, dispatch] = useReducer(reducer, { count: 0 });
  

20. Creating reusable button component

function CustomButton({ onClick, label }) {
  return <button onClick={onClick}>{label}</button>;
}
  

21. Add class based on condition

const className = isActive ? 'active' : 'inactive';
return <div className={className}>Status</div>;
  

22. Set document title with useEffect

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);
  

23. Focus input on mount

useEffect(() => {
  inputRef.current.focus();
}, []);
  

24. React Router example

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</BrowserRouter>
  

25. Redirect with useNavigate

const navigate = useNavigate();
useEffect(() => {
  navigate('/login');
}, []);
  

26. Animate with CSS transitions

<div className={`box ${isVisible ? 'show' : 'hide'}`}></div>
  

27. Show loading while fetching

return isLoading ? <p>Loading...</p> : <p>Data loaded</p>;
  

28. React component composition

function Card({ header, body }) {
  return (
    <div>
      <h3>{header}</h3>
      <p>{body}</p>
    </div>
  );
}
  

29. Toggle visibility

const [show, setShow] = useState(false);
<button onClick={() => setShow(!show)}>Toggle</button>
{show && <p>Visible Content</p>}
  

30. Set default props

function Button({ label = "Click me" }) {
  return <button>{label}</button>;
}
  

31. Render props pattern

function DataProvider({ render }) {
  const data = "Hello from render props!";
  return render(data);
}

// Usage:
<DataProvider render={(data) => <p>{data}</p>} />
  

32. Higher Order Component (HOC)

function withLogger(Component) {
  return function WrappedComponent(props) {
    console.log('Rendering', Component.name);
    return <Component {...props} />;
  }
}
  

33. Debouncing input

useEffect(() => {
  const timer = setTimeout(() => {
    // do something
  }, 300);
  return () => clearTimeout(timer);
}, [inputValue]);
  

34. useLayoutEffect vs useEffect

useLayoutEffect(() => {
  // Runs before paint
}, []);
  

35. Unit test a component

// Jest & React Testing Library
test('renders greeting', () => {
  render(<Greeting />);
  expect(screen.getByText(/hello/i)).toBeInTheDocument();
});
  

36. Portal usage

return ReactDOM.createPortal(
  <div>I’m a modal</div>,
  document.getElementById('modal-root')
);
  

37. Compound component pattern

function Tabs({ children }) {
  return <div>{children}</div>;
}

Tabs.Panel = function Panel({ children }) {
  return <div>{children}</div>;
};
  

38. useImperativeHandle example

useImperativeHandle(ref, () => ({
  focus: () => {
    inputRef.current.focus();
  }
}));
  

39. Using Suspense with data

const resource = fetchData();

function Component() {
  const data = resource.read();
  return <p>{data}</p>;
}
  

40. useMemo for expensive computation

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  

41. Authentication context

const AuthContext = createContext();
function useAuth() {
  return useContext(AuthContext);
}
  

42. Theme toggler with Context

const ThemeContext = createContext();
function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}
  

43. Performance optimization with memo

const FastComponent = React.memo(function({ name }) {
  return <p>Hi {name}</p>;
});
  

44. Render fallback while loading

<Suspense fallback={<div>Loading...</div>}>
  <LazyComponent />
</Suspense>
  

45. Global state with Zustand

const useStore = create(set => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 }))
}));
  

46. Custom event bus with context

const EventBus = createContext();

function useEventBus() {
  return useContext(EventBus);
}
  

47. Nested routing with React Router

<Route path="dashboard" element={<Dashboard />}>
  <Route path="settings" element={<Settings />} />
</Route>
  

48. Keyboard event handler

useEffect(() => {
  const handleKey = (e) => {
    if (e.key === 'Enter') alert('Enter pressed');
  };
  window.addEventListener('keydown', handleKey);
  return () => window.removeEventListener('keydown', handleKey);
}, []);
  

49. IntersectionObserver for lazy loading

const observer = new IntersectionObserver(entries => {
  if (entries[0].isIntersecting) {
    // Load content
  }
});
observer.observe(ref.current);
  

50. Copy to clipboard

navigator.clipboard.writeText('Copied text');
  

51. Resize listener hook

useEffect(() => {
  const onResize = () => setSize(window.innerWidth);
  window.addEventListener('resize', onResize);
  return () => window.removeEventListener('resize', onResize);
}, []);
  

52. Mouse position tracker

useEffect(() => {
  const update = e => setPos({ x: e.clientX, y: e.clientY });
  window.addEventListener('mousemove', update);
  return () => window.removeEventListener('mousemove', update);
}, []);
  

53. Persist state with localStorage

useEffect(() => {
  localStorage.setItem('count', count);
}, [count]);
  

54. Infinite scroll setup

useEffect(() => {
  window.onscroll = () => {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
      loadMore();
    }
  };
}, []);
  

55. useId for accessibility

const id = useId();
return <label htmlFor={id}>Name</label><input id={id} />;
  

56. Detect dark mode

const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  

57. Add transition with framer-motion

<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} />
  

58. Nested context providers

<ThemeProvider>
  <AuthProvider>
    <App />
  </AuthProvider>
</ThemeProvider>
  

59. Log state changes with useEffect

useEffect(() => {
  console.log("State changed:", value);
}, [value]);
  

60. Prevent re-renders with useCallback

const memoizedCallback = useCallback(() => {
  doSomething();
}, [dependency]);
  

61. Handle form with useReducer

const formReducer = (state, action) => ({ ...state, [action.name]: action.value });

const [form, dispatch] = useReducer(formReducer, { name: "", email: "" });

<input name="name" onChange={(e) => dispatch(e.target)} />
  

62. Delay rendering until after mount

const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return null;
  

63. Toggle boolean state

const [open, setOpen] = useState(false);
const toggle = () => setOpen(prev => !prev);
  

64. Custom debounce hook

function useDebounce(value, delay) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const handler = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
  return debounced;
}
  

65. Accessible button

<button aria-label="Close" onClick={handleClose}>X</button>
  

66. Custom hook for localStorage

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const saved = localStorage.getItem(key);
    return saved ? JSON.parse(saved) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}
  

67. Fetch on prop change

useEffect(() => {
  fetch(`/api/user/${id}`).then(res => res.json()).then(setUser);
}, [id]);
  

68. Dynamic imports

const LazyComponent = React.lazy(() => import('./MyComponent'));
  

69. Focus input on mount

useEffect(() => {
  inputRef.current.focus();
}, []);
  

70. Animate list items

items.map((item, i) => (
  <motion.div key={i} initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
    {item}
  </motion.div>
))
  

71. usePrevious hook

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}
  

72. Throttle hook

function useThrottle(value, delay) {
  const [throttled, setThrottled] = useState(value);
  const lastRan = useRef(Date.now());

  useEffect(() => {
    const handler = setTimeout(() => {
      if (Date.now() - lastRan.current >= delay) {
        setThrottled(value);
        lastRan.current = Date.now();
      }
    }, delay);
    return () => clearTimeout(handler);
  }, [value, delay]);

  return throttled;
}
  

73. Toast notification

const showToast = () => {
  alert('This is a toast!');
}
  

74. Error boundary class

class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    return this.state.hasError ? <h1>Something went wrong</h1> : this.props.children;
  }
}
  

75. Controlled vs uncontrolled input

<input value={name} onChange={e => setName(e.target.value)} />
<input defaultValue="default" />
  

76. Dynamic themes with CSS variables

document.documentElement.style.setProperty('--main-bg', dark ? '#000' : '#fff');
  

77. Prevent page scroll

useEffect(() => {
  document.body.style.overflow = 'hidden';
  return () => (document.body.style.overflow = 'auto');
}, []);
  

78. Ref forwarding

const Input = React.forwardRef((props, ref) => <input ref={ref} {...props} />);
  

79. Prop types

MyComponent.propTypes = {
  name: PropTypes.string.isRequired,
};
  

80. Environment variables

const api = process.env.REACT_APP_API_URL;
  

81. Export multiple components

export const A = () => <div>A</div>;
export const B = () => <div>B</div>;
  

82. Batching state updates

setCount(c => c + 1);
setCount(c => c + 1);
  

83. Prevent memory leaks

let isMounted = true;
fetch(url).then(res => {
  if (isMounted) setData(res);
});
return () => { isMounted = false; };
  

84. useEffect cleanup

useEffect(() => {
  const id = setInterval(log, 1000);
  return () => clearInterval(id);
}, []);
  

85. Global error handler

window.onerror = (msg) => console.error("Global Error:", msg);
  

86. Simulate API latency

await new Promise(res => setTimeout(res, 1000));
  

87. Skeleton loader

<div className="skeleton"></div>
<style>.skeleton { background: #ccc; height: 20px; }</style>
  

88. Retry API on failure

async function fetchWithRetry(url, retries = 3) {
  try {
    return await fetch(url);
  } catch (err) {
    if (retries > 0) return fetchWithRetry(url, retries - 1);
    throw err;
  }
}
  

89. Render component based on role

{role === 'admin' ? <AdminPanel /> : <UserPanel />}
  

90. Fallback UI on error

<ErrorBoundary>
  <MainComponent />
</ErrorBoundary>
  

91. Optimize list with react-window

import { FixedSizeList as List } from 'react-window';
<List height={150} itemCount={1000} itemSize={35} width={300}>
  {({ index, style }) => <div style={style}>Item {index}</div>}
</List>
  

92. How do you lazy load images in React?

<img loading="lazy" src="image.jpg" alt="example" />
  

93. How do you detect clicks outside a component?

useEffect(() => {
  function handleClick(e) {
    if (!ref.current.contains(e.target)) onClose();
  }
  document.addEventListener("mousedown", handleClick);
  return () => document.removeEventListener("mousedown", handleClick);
}, []);
  

94. How do you fetch data only once when the component mounts?

useEffect(() => {
  fetch("/api").then(res => res.json()).then(setData);
}, []);
  

95. How can you memoize a computed value?

const expensiveValue = useMemo(() => compute(num), [num]);
  

96. How can you animate a component when it enters or leaves?

import { CSSTransition } from "react-transition-group";
<CSSTransition in={show} timeout={300} classNames="fade">
  <div>Content</div>
</CSSTransition>
  

97. How do you handle file uploads in React?

<input type="file" onChange={e => setFile(e.target.files[0])} />
  

98. How can you conditionally apply a class in JSX?

<div className={isActive ? "active" : ""}>Hello</div>
  

99. How to use async/await inside useEffect?

useEffect(() => {
  const fetchData = async () => {
    const res = await fetch("/api");
    const data = await res.json();
    setData(data);
  };
  fetchData();
}, []);
  

100. How to highlight selected item in a list?

{items.map((item, i) => (
  <div key={i} className={selected === i ? "selected" : ""} onClick={() => setSelected(i)}>
    {item}
  </div>
))}
  

101. How to copy text to clipboard?

navigator.clipboard.writeText("Copied text");
  

102. How to create an accordion component?

const [open, setOpen] = useState(false);
<button onClick={() => setOpen(!open)}>Toggle</button>
{open && <div>Accordion Content</div>}
  

103. How to dynamically add or remove inputs?

const [fields, setFields] = useState([""]);
const addField = () => setFields([...fields, ""]);
const removeField = i => setFields(fields.filter((_, idx) => idx !== i));
  

104. How to restrict re-renders in a list?

const MemoItem = React.memo(({ value }) => <div>{value}</div>);
  

105. How do you implement a custom dropdown?

const [open, setOpen] = useState(false);
<div onClick={() => setOpen(!open)}>Menu</div>
{open && <ul><li>Item</li></ul>}
  

106. How to scroll to an element?

const ref = useRef();
ref.current.scrollIntoView({ behavior: "smooth" });
  

107. How to create a multi-step form?

const [step, setStep] = useState(1);
{step === 1 && <StepOne />}
{step === 2 && <StepTwo />}
  

108. How to use multiple refs in a loop?

const refs = useRef([]);
refs.current[index] = el;
<input ref={el => refs.current[i] = el} />
  

109. How to debounce a search input?

const debounced = useDebounce(search, 300);
useEffect(() => searchAPI(debounced), [debounced]);
  

110. How to detect screen size changes?

useEffect(() => {
  const update = () => setWidth(window.innerWidth);
  window.addEventListener("resize", update);
  return () => window.removeEventListener("resize", update);
}, []);
  

111. How to upload image preview?

const handleChange = e => {
  const file = e.target.files[0];
  const url = URL.createObjectURL(file);
  setPreview(url);
};
  

112. How to group a list of items?

const groups = items.reduce((acc, item) => {
  (acc[item.category] ||= []).push(item);
  return acc;
}, {});
  

113. How to use a portal?

ReactDOM.createPortal(<Modal />, document.getElementById("portal"));
  

114. How to listen for keypress?

useEffect(() => {
  const handleKey = e => e.key === "Escape" && close();
  document.addEventListener("keydown", handleKey);
  return () => document.removeEventListener("keydown", handleKey);
}, []);
  

115. How to get geolocation?

navigator.geolocation.getCurrentPosition(pos => console.log(pos.coords));
  

116. How to use transition effect on toggle?

<div style={{ transition: "0.3s", opacity: show ? 1 : 0 }}>Content</div>
  

117. How to sync scroll position?

const syncScroll = () => {
  ref2.current.scrollTop = ref1.current.scrollTop;
};
<div onScroll={syncScroll} ref={ref1}></div>
  

118. How to generate unique keys?

items.map(item => <div key={item.id}>{item.name}</div>)
  

119. How to create a toggle theme button?

const toggleTheme = () => setTheme(prev => (prev === "dark" ? "light" : "dark"));
  

120. How to reset form inputs?

const reset = () => setForm({ name: "", email: "" });
  

121. How to pass props to children?

React.cloneElement(children, { newProp: value })
  

122. How to create a controlled input?

const [value, setValue] = useState("");
<input value={value} onChange={e => setValue(e.target.value)} />
  

123. How to implement dark mode in React?

const [dark, setDark] = useState(false);
<div className={dark ? "dark" : ""}>App</div>
<button onClick={() => setDark(!dark)}>Toggle Theme</button>
  

124. How to store a token in localStorage?

localStorage.setItem("token", "abc123");
const token = localStorage.getItem("token");
  

125. How to focus an input on mount?

const inputRef = useRef();
useEffect(() => inputRef.current.focus(), []);
<input ref={inputRef} />
  

126. How to use React Fragment?

<>
  <h1>Title</h1>
  <p>Text</p>
</>
  

127. How to update an object in state?

setUser(prev => ({ ...prev, name: "New Name" }));
  

128. How to bind functions in class components?

this.handleClick = this.handleClick.bind(this);
  

129. How to share state between siblings?

Lift the shared state to the parent and pass via props.
  

130. How to use useReducer for form handling?

const reducer = (state, action) => ({ ...state, [action.name]: action.value });
const [form, dispatch] = useReducer(reducer, {});
<input name="email" onChange={e => dispatch(e.target)} />
  

131. How to prevent event bubbling?

event.stopPropagation();
  

132. How to use a default prop in functional components?

function Button({ label = "Click Me" }) {
  return <button>{label}</button>;
}
  

133. How to chain promises in useEffect?

useEffect(() => {
  fetch(url)
    .then(res => res.json())
    .then(data => console.log(data));
}, []);
  

134. How to render a list with unique keys?

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

135. How to implement a modal dialog?

const [show, setShow] = useState(false);
{show && <div className="modal">Modal Content</div>}
  

136. How to fetch and paginate data?

useEffect(() => {
  fetch(`/api?page=${page}`).then(res => res.json()).then(setData);
}, [page]);
  

137. How to optimize re-renders with React.memo?

const MemoComponent = React.memo(MyComponent);
  

138. How to make a counter with hooks?

const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1)}>Increment</button>
  

139. How to apply inline styles?

<div style={{ color: "red", fontSize: "20px" }}>Hello</div>
  

140. How to show and hide password?

const [type, setType] = useState("password");
<input type={type} />
<button onClick={() => setType(type === "password" ? "text" : "password")}>Toggle</button>
  

141. How to set a timeout in React?

useEffect(() => {
  const timer = setTimeout(() => setShow(true), 1000);
  return () => clearTimeout(timer);
}, []);
  

142. How to filter a list in JSX?

{items.filter(i => i.includes("a")).map(i => <div>{i}</div>)}
  

143. How to toggle boolean state?

setOpen(prev => !prev);
  

144. How to prevent default form submit?

const handleSubmit = e => {
  e.preventDefault();
  // handle data
};
  

145. How to redirect with React Router?

import { useNavigate } from "react-router-dom";
const nav = useNavigate();
nav("/home");
  

146. How to track online/offline status?

const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
  window.addEventListener("online", () => setOnline(true));
  window.addEventListener("offline", () => setOnline(false));
}, []);
  

147. How to dynamically render components?

const components = { A: AComponent, B: BComponent };
const Dynamic = components[type];
<Dynamic />
  

148. How to export and import components?

// MyComponent.js
export default function MyComponent() { return <div>Hi</div>; }

// App.js
import MyComponent from "./MyComponent";
  

149. How to delay an animation?

style={{ transitionDelay: "0.5s" }}
  

150. How to use optional chaining in JSX?

<div>{user?.name}</div>
  

151. How to remove item from array in state?

setItems(prev => prev.filter((_, idx) => idx !== index));
  

152. What is the purpose of the `key` prop in React?

The `key` prop helps React identify which items have changed, been added, or removed in lists, improving performance when rendering lists of components.
  

153. How do you conditionally render elements in React?

You can conditionally render elements in React using JavaScript expressions like `if`, ternary operators, or logical `&&` operators within JSX.
<div>{isLoggedIn ? "Welcome back!" : "Please log in"}

154. What is the difference between `componentWillMount` and `componentDidMount`?

`componentWillMount` is called right before a component is mounted, whereas `componentDidMount` is called after the component has mounted and is ready for interactions.
  

155. What is React Router?

React Router is a library for adding routing capabilities to a React application. It enables navigation between different components/views based on URL changes.
  

156. How do you create a route in React Router?

Using the `Route` component from React Router, you define the path and the component to render for that path.
<Route path="/home" component={Home} />
  

157. What is `useContext` used for in React?

`useContext` is a hook that allows you to access the value of a context without the need to pass it down manually through props.
  

158. What is `React.memo`?

`React.memo` is a higher-order component that memoizes a component, preventing unnecessary re-renders if the props have not changed.
  

159. How can you handle form submissions in React?

You can handle form submissions in React by using the `onSubmit` event and controlling form elements with state. Example:
<form onSubmit={handleSubmit}>
  <input type="text" value={inputValue} onChange={handleChange} />
  <button type="submit">Submit</button>
</form>
  

160. What are propTypes in React?

`propTypes` is a way to define the expected types of props that a component should receive, helping to validate the props passed to a component.
  

161. What is the purpose of the `React.StrictMode`?

`React.StrictMode` is a wrapper component that helps identify potential problems in an application. It activates additional checks and warnings for components during development.
  

162. What are fragments in React?

Fragments let you group multiple elements without adding extra nodes to the DOM. They are often used to return multiple elements from a component.
<React.Fragment><div>Hello</div></React.Fragment>
  

163. What is the purpose of `useEffect` cleanup?

The cleanup function inside `useEffect` is used to clean up side effects like subscriptions, timers, or event listeners when a component unmounts or before it re-renders.
  

164. How can you optimize performance in React?

You can optimize React performance by using `React.memo` for memoization, lazy loading components, using PureComponent, avoiding inline functions, and utilizing `useMemo` and `useCallback`.