Beginner Level (0–1 Years)

1. What is JSX, and how does it work in React?

Answer:

JSX is a syntax extension that looks like HTML but allows embedding JavaScript expressions. It’s transpiled into React.createElement calls to create React elements. For example, <div>{name}</div> becomes React.createElement('div', null, name).

2. How do you handle events in React, like a button click?

Answer:

Use camelCase event handlers like onClick and pass a function. Example: <button onClick={() => setCount(count + 1)}>Click</button>. Avoid calling functions directly in the prop (e.g., onClick={myFunction()}) to prevent immediate execution.

3. What’s the difference between props and state in React?

Answer:

Props are read-only data passed from a parent to a child component. State is mutable data managed within a component using useState or this.state. Props drive data flow, while state handles internal changes.

4. How do you perform conditional rendering in React?

Answer:

Use JavaScript operators like &&, ||, or ternary operators, or if statements outside the return. Example: {isLoggedIn ? <Profile /> : <Login />} or if (isLoggedIn) return <Profile />;.

5. What is React Router, and how do you create a basic route?

Answer:

React Router is a library for navigation in React apps. Use <BrowserRouter>, <Route>, and <Link> to define routes. Example: <Route path="/home" component={Home} /> renders the Home component at /home.

6. What’s the difference between a function component and a class component in React?

Answer:

Function components are JavaScript functions that can manage state and side effects using Hooks. Class components are ES6 classes that use state and lifecycle methods. Function components are preferred in modern React due to simplicity, but class components are still used in legacy codebases.

7. Why are keys important in lists?

Answer:

Keys help React identify which items in a list have changed, been added, or removed, enabling efficient updates. For example, use <li key={item.id}>{item.name}</li> to assign unique keys. Without unique keys, React may re-render inefficiently, causing unexpected behavior.

8. What does React.memo() do, and when should you use it?

Answer:

React.memo() is a higher-order component that memoizes a functional component, preventing re-renders if props remain shallowly equal. Use it for performance optimization in pure functional components with stable or memoized props.

9. Does React re-render a component if its parent re-renders?

Answer:

Yes, a component re-renders when its parent re-renders unless memoized with React.memo() (for function components) or PureComponent (for class components). React.memo() prevents re-renders if props are shallowly equal.

10. What’s a potential issue with using index as a key in a list?

Answer:

Using an index as a key can cause issues when the list order changes, as React relies on keys to match items. For example, reordering a to-do list may lead to incorrect DOM updates or form input mismatches. Always use a unique identifier, like an item’s ID, instead.

11. Can a React component return multiple elements without a wrapper?

Answer:

Yes, using fragments (<></> or <React.Fragment>) allows returning multiple elements without adding extra DOM nodes, keeping the markup clean.

12. What’s wrong with modifying props inside a component?

Answer:

Props are read-only in React. Modifying them violates the unidirectional data flow and immutability principles, leading to unpredictable rendering and bugs.

13. When does a component re-render in React?

Answer:

A component re-renders when its state, props, or context changes, or when its parent re-renders (unless memoized).

14. What’s a potential issue with calling hooks conditionally?

Answer:

Hooks must be called unconditionally in the same order on every render, per the Rules of Hooks. Conditional calls disrupt React’s internal tracking, causing runtime errors or unpredictable behavior.

15. What does a React function component render if it contains a conditional statement that always evaluates to true, returning one div, with another div as the default return?

Answer:

It renders <div>Hi</div>, as the conditional statement is always true, returning the first div. This tests understanding of control flow in function components.

16. Why doesn’t state update immediately after calling setState or useState?

Answer:

State updates via setState or useState are asynchronous and queued for the next render cycle. You won’t see the updated value immediately after calling the setter.

17. What is the purpose of a cleanup function in useEffect?

Answer:

The cleanup function in useEffect runs before the effect re-runs or when the component unmounts, preventing memory leaks from side effects like timers or subscriptions. For example: return () => clearInterval(timer);.

18. Can you update state based on the current state?

Answer:

Yes, use the functional update form, setCount(prev => prev + 1), to ensure updates are based on the latest state, especially during batched or asynchronous updates.

19. What is a controlled component in React?

Answer:

A controlled component is a form element, like an input, whose value is managed by React state via the value prop and onChange handler. Example: <input value={state} onChange={e => setState(e.target.value)} />.

20. How does React identify which components need to be re-rendered?

Answer:

React uses a virtual DOM and reconciliation to compare the previous and current component trees. It updates the real DOM only where state, props, or context changes necessitate it.

21. Can props cause a re-render?

Answer:

Yes, new props trigger a re-render unless the component is memoized with React.memo() and props are shallowly equal. Ensure props like objects or functions are stable to avoid unnecessary re-renders.

22. What does lifting state up mean?

Answer:

Lifting state up means moving state to a common parent component to share it with child components via props. For example, a counter state in a parent can be passed to two sibling buttons to synchronize their behavior.

23. Can you use hooks in class components?

Answer:

No. Hooks can only be used in function components or custom hooks. Class components must use lifecycle methods instead.

24. How can you prevent unnecessary re-renders?

Answer:

Prevent unnecessary re-renders using React.memo for components, useMemo to memoize computed values, and useCallback to memoize functions. Avoid creating new objects or functions in render to maintain prop stability.

25. What does it mean that React is declarative?

Answer:

React is declarative, meaning you define what the UI should look like based on state, and React handles DOM updates. Unlike imperative approaches (e.g., jQuery’s manual DOM changes), React abstracts the “how” of rendering.


👋 Need top React developers for your project? Interview this week!

Fill out the form to book a call with our team. We’ll match you to the top developers who meet your requirements, and you’ll be interviewing this week!

Request for Service


Intermediate Level (1–3 Years)

1. What are error boundaries in React, and how do you implement them?

Answer:

Error boundaries are components that catch JavaScript errors in their child tree, displaying fallback UI. Implement with a class component using static getDerivedStateFromError or componentDidCatch:


class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) return

Error

;
    return this.props.children;
  }
}
      

2. How do you create a custom hook in React?

Answer:

A custom hook is a function starting with `use` that encapsulates reusable logic. Example:


function useWindowSize() {
  const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight });
  useEffect(() => {
    const handleResize = () => setSize({ width: window.innerWidth, height: window.innerHeight });
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return size;
}
      

3. How do you implement navigation with React Router?

Answer:

Use React Router’s BrowserRouter, Route, Link, and useNavigate. Example:



  } />
  Home

      

Programmatic navigation: const navigate = useNavigate(); navigate('/home');

4. How do you use TypeScript with React components?

Answer:

Define props with interfaces or types. Example:


interface Props {
  name: string;
  age?: number;
}
const Greeting: React.FC = ({ name, age = 0 }) =>
Hello, {name}, age {age}
;
       Use React.FC for function components to infer children and other React-specific types.

5. What are common patterns for data fetching in React?

Answer:

Fetch data in useEffect with state for loading and error:


      useEffect(() => {
        setLoading(true);
        fetch(url)
          .then(res => res.json())
          .then(setData)
          .catch(setError)
          .finally(() => setLoading(false));
      }, []);
    

Alternatively, use libraries like SWR or React Query for caching and refetching.

6. How does React’s reconciliation algorithm work?

Answer:

React’s reconciliation algorithm compares the virtual DOM with its previous version using a diffing process. It updates only changed DOM nodes for efficiency. React assumes components of different types yield different trees and uses keys to match list items. If types or keys mismatch, React rebuilds the subtree.

7. What is the difference between useMemo and useCallback?

Answer:

useMemo memoizes a computed value, while useCallback memoizes a function reference. Example: const sum = useMemo(() => computeSum(data), [data]) for calculations, and const handleClick = useCallback(() => setCount(count + 1), [count]) for functions.

8. Why is state mutation a bad practice in React?

Answer:

Mutating state directly (e.g., state.count++) bypasses React’s change detection, causing unpredictable rendering. State should be immutable, updated via setters like setState or useState, ensuring React re-renders correctly.

9. How can you share logic between components in React?

Answer:

Share logic using custom hooks (preferred for simplicity), higher-order components (HOCs), render props, or composition with context. Custom hooks like useAuth are the most idiomatic in modern React.

10. What is prop drilling and how do you avoid it?

Answer:

Prop drilling is passing props through intermediate components to reach nested ones. Avoid it with React Context, component composition, or state management libraries like Redux or Zustand. Context is often sufficient for simpler cases.

11. How does React handle event delegation?

Answer:

React uses a synthetic event system, attaching event listeners to the root DOM node for delegation. Events bubble through the virtual DOM, normalizing cross-browser event behavior and improving performance.

12. What’s the difference between controlled and uncontrolled components?

Answer:

Controlled components manage their value via React state (e.g., <input value={state} onChange={e => setState(e.target.value)} />). Uncontrolled components use DOM state via refs (e.g., <input ref={inputRef} />)). Controlled components offer more control, while uncontrolled are simpler for basic forms.

13. How does React determine if a component should re-render?

Answer:

React re-renders when a component’s props change, state, or context change, or when its parent re-renders. For function components, React.memo() applies shallow comparison to prevent re-renders if props are unchanged.

14. What are the rules of hooks?

Answer:

Hooks must be called at the top level of a component or custom hook. They cannot be called inside loops, conditions, or nested functions. Hooks must always be called in the same order.

15. What happens when you pass a new function as a prop every render?

Answer:

It causes child components to re-render, breaking memoization (e.g., with React.memo). Use useCallback to memoize the function, ensuring stable references (e.g., const handleClick = useCallback(() => {}, [])).

16. How can you optimize a large list in React?

Answer:

Optimize large lists with virtualization libraries like react-window or react-virtualized to virtualized render only visible items. Ensure stable, unique keys for list items to improve React’s diffing efficiency.

17. What is the purpose of the key prop in React?

Answer:

The key prop helps React identify which list items changed, were added, or removed. Keys must be unique and stable among siblings to prevent re-mounting or incorrect updates.

18. Explain useRef and a common use case.

Answer:

useRef returns a mutable ref object that persists across renders. Common use cases include accessing DOM elements (e.g., useRef.current.focused()) or storing values without triggering re-renders.

19. What is the difference between useEffect and useLayoutEffect?

Answer:

useLayoutEffect runs synchronously before the browser paints, while useEffect runs asynchronously after painting. Use useLayoutEffect for DOM measurements, but sparingly, as it can block rendering.

20. How do you test a React component?

Answer:

Test React components with React Testing Library for rendering and user interactions, paired with Jest for assertions and mocking. Example: render(\\<button\\>\\</button\\>); expect(screen.getByText('Click')).toBeInTheDocument();

21. What is a higher-order component (HOC)?

Answer:

An HOC is a function that takes a component and returns an enhanced component (e.g., const withLogger = Component => props => { console.log(props); return ; }). Custom hooks are often preferred in modern React.

22. What is context and how is it different from Redux?

Answer:

Context is a built-in API for passing data without prop drilling, ideal for simpler global state (e.g., themes). Redux offers advanced features like middleware and debugging, better for complex state management.

23. Why might you get an infinite loop inside useEffect?

Answer:

An infinite loop in useEffect occurs if dependencies change on every render or are omitted incorrectly (e.g., useEffect(() => setCount(count + 1), [count])). Fix by ensuring stable dependencies or using an empty array for one-time effects.

24. What is a render prop pattern?

Answer:

A render prop is a pattern where a component’s child is a function that receives props to render (e.g., } />). Custom hooks often replace render props in modern React.

25. How would you implement debouncing in a React input field?

Answer:

Implement debouncing with useEffect and setTimeout:


useEffect(() => {
  const handler = setTimeout(() => setDebounced(value), 500);
  return () => clearTimeout(handler);
}, [value]);
      

Alternatively, use libraries like lodash.debounce for simplicity.

26. What does lazy loading mean in React?

Answer:

Lazy loading defers loading components until needed, reducing initial bundle size. Use React.lazy and Suspense: const LazyComponent = React.lazy(() => import('./Component')); }>`.

27. What is the difference between mounting and rendering in React?

Answer:

Mounting is adding a component to the DOM for the first time (e.g., triggering useEffect with []). Rendering occurs during mounting and updates when React computes the UI based on props, state, or context.

28. Why might you prefer useReducer over useState?

Answer:

useReducer is more preferred for complex state logic or when state transitions depend on previous state (e.g., managing a multi-step form). It’s used a reducer function for predictable updates via actions.

29. What are the limitations of the Context API?

Answer:

Frequent context value updates can re-render all consumers, impacting performance. It’s less suited for high-frequency updates (e.g., mouse position). Optimize by splitting contexts or memoizing provider values.

30. What is Suspense used for?

Answer:

Suspense displays a fallback UI while lazy-loaded components load (e.g., }>...). In the future, it may support data fetching with experimental APIs.

31. Can you nest multiple providers in React?

Answer:

Yes. You can nest multiple context providers to scope values separately:


import React from 'react';
const ThemeContext = React.createContext();
const UserContext = React.createContext();

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <UserContext.Provider value={{ name: 'User' }}>
        <Component />
      </UserContext.Provider>
    </ThemeContext.Provider>
  );
}
        

32. How would you memoize an expensive calculation in React?

Answer:

Use useMemo:


const result = useMemo(() => expensiveFunction(data), [data]);
      

This ensures the function only recalculates when dependencies change.

33. Can a component have multiple useEffect calls?

Answer:

Yes. Having multiple useEffect calls helps organize logic by concern (e.g., API call in one, subscriptions in another).

34. How do you manage side effects in React?

Answer:

Manage side effects with useEffect for async tasks (e.g., fetching data) or useLayoutEffect for synchronous DOM updates. Return cleanup functions to prevent memory leaks (e.g., clearInterval(timer)).

35. Can hooks replace all class component use cases?

Answer:

Hooks can handle most class component use cases (e.g., state, lifecycle methods), but class components are still used for specific cases like error boundaries, which hooks can’t handle.

36. What are common causes of performance issues in React?

Answer:

Common performance issues include frequent re-renders, unstable props, large DOM trees, unoptimized lists, or heavy render computations. Use React Profiler or DevTools to identify and fix bottlenecks.

37. What does forwardRef do?

Answer:

forwardRef allows a component to pass a ref to a child DOM element or component, often used in reusable library components like custom inputs (e.g., ).

38. How would you delay rendering a component until data is ready?

Answer:

Delay rendering with conditional rendering (data ? : ) or Suspense for lazy components. For async data, use state to track loading: useEffect(() => { fetchData().then(setData); }, []).

39. What’s the difference between SSR and CSR in React?

Answer:

Server-Side Rendering (SSR) renders HTML on the server (e.g., Next.js), improving SEO and initial load time. Client-Side Rendering (CSR) renders in the browser after JavaScript loads, suitable for dynamic apps but slower initially.

40. What is a pure component?

Answer:

A pure component renders the same output for the same props and state. React.PureComponent for classes and React.memo for functions use shallow comparison to skip re-renders if inputs are unchanged.

41. How can you avoid stale closures in useEffect?

Answer:

Stale closures occur when useEffect captures outdated variables from previous renders. Fix by including all used variables in the dependency array or using useRef for mutable values (e.g., ref.current = value).

42. What are compound components in React?

Answer:

Compound components are components that work together, sharing state implicitly (e.g., Content). They use context or props to coordinate behavior.

43. How would you implement a global state in React without Redux?

Answer:

Use React Context with useReducer for global state or libraries like Zustand or Jotai. Context is simpler but may cause re-renders for frequent updates, so optimize with memoization.

44. What are controlled animations in React?

Answer:

Controlled animations are driven by React state or props, using libraries like Framer Motion (e.g., ). They allow precise control over animation states.

45. What’s the use of defaultProps in functional components?

Answer:

In functional components, use default parameters (e.g., function Button({ text = 'Click' }) {}) instead of defaultProps, which is deprecated in modern React for functional components.

46. What is hydration in React?

Answer:

Hydration is React attaching event listeners to server-rendered HTML (SSR) to make it interactive. Mismatches between server and client output (e.g., different DOM structures) cause hydration errors.

47. How do you ensure a component doesn’t re-render unnecessarily?

Answer:

Prevent re-renders with React.memo for components, useCallback for functions, and to useMemo for computed values. Avoid creating new objects or arrays in render unless memoized.

48. What’s the difference between shallow and deep comparison?

Answer:

Shallow comparison checks top-level properties for equality, while deep comparison checks nested values. React uses shallow comparison in React.memo and PureComponent to optimize re-renders.

49. How would you cancel a fetch request in a component?

Answer:

Cancel a fetch with AbortController:


useEffect(() => {
  const controller = new AbortController();
  fetch(url, { signal: controller.signal })
    .then(res => res.json())
    .then(setData);
  return () => controller.abort();
}, []);
       );

50. What is tree shaking, and how does it affect React apps?

Answer:

Tree shaking removes unused code during bundling (e.g., with Webpack or Rollup), reducing React app bundle size by eliminating unused components or functions.


LATAM-Image-V2.png

Hire Top LATAM Developers: Guide

We’ve prepared this guide that covers  benefits, costs, recruitment, and remote team management to a succesful hiring of developers in LATAM. 

Fill out the form to get our guide.

Gated content


Advanced Level (3+ Years)

1. How do you use React Query for efficient data fetching?

Answer:

React Query manages data fetching, caching, and updates: const { data, isLoading, error } = useQuery(['key'], () => fetchData());. It handles refetching, caching, and optimistic updates, reducing manual state management.

2. What is server-side streaming in Next.js, and how does it work?

Answer:

Server-side streaming in Next.js (App Router) streams RSC payloads incrementally, improving perceived performance. Use Suspense boundaries and async components: async function Page() { const data = await fetchData(); return }>... };.

3. How do you create a custom React renderer?

Answer:

Use ReactReconciler to create a custom renderer: const reconciler = ReactReconciler(hostConfig); reconciler.render(, container);. Define a hostConfig for your target (e.g., canvas, WebGL) to manage rendering logic.

4. What are common pitfalls in React Concurrent Mode?

Answer:

Pitfalls include stale closures, tearing in external stores, and double rendering in Strict Mode. Use useSyncExternalStore, ensure correct useEffect dependencies, and test with Strict Mode enabled.

5. How do you use advanced TypeScript patterns in React?

Answer:

Use generics and conditional types: type Props = { type: T; value: T extends 'text' ? string : number }; const Component = ({ type, value }: Props) => .... This ensures type-safe dynamic props.

6. What are React Server Components, and how do they differ from traditional components?

Answer:

React Server Components (RSC) run only on the server, sending UI with minimal client-side JavaScript. Unlike client components, they don’t use state or effects but can be async (e.g., async function Component() { const data = await fetchData(); }). They reduce bundle size and improve performance in frameworks like Next.js.

7. Explain the significance of concurrent rendering in React.

Answer:

Concurrent rendering in React 18 allows interrupting and prioritizing updates, improving responsiveness. It powers features like startTransition, useDeferredValue, and selective hydration, pausing non-urgent renders for smoother user experiences.

8. How does useTransition work in React?

Answer:

useTransition marks updates as non-urgent: const [isPending, startTransition] = useTransition(); startTransition(() => setFilter(newValue));. Example: Use it to filter a large list without blocking input updates.

9. Describe the hydration mismatch warning in React and how to handle it.

Answer:

A hydration mismatch occurs when server-rendered HTML differs from client-rendered output (e.g., due to Date.now(), browser-specific logic, or third-party scripts). Fix by ensuring consistent rendering, using useEffect for client-only logic, or adding suppressHydrationWarning for unavoidable cases.

10. How would you implement error boundaries in React?

Answer:

Error boundaries are class components that catch errors in their child tree using static getDerivedStateFromError or componentDidCatch:

class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, info) { logError(error, info); } render() { return this.state.hasError ?  : this.props.children; } }

. Hooks cannot implement error boundaries.

11. What are React’s rendering phases and what happens in each?

Answer:

React’s render phase calculates the virtual DOM diff using Fiber, determining what to render. The commit phase applies changes to the real DOM. Side effects (e.g., useEffect) run post-commit, enabling concurrent rendering.

12. What’s the purpose of useDeferredValue?

Answer:

useDeferredValue defers rendering of non-urgent UI parts: const deferredValue = useDeferredValue(value);. Example: Use it to render search results while keeping input responsive, deferring heavy list updates.

13. What is Suspense for Data Fetching, and how does it differ from traditional fetching?

Answer:

Suspense for Data Fetching (experimental) pauses rendering until data resolves, using libraries like Relay or Next.js. Unlike traditional fetching with manual loading states, it integrates with Suspense for fallbacks: }>.... Stable uses focus on lazy-loaded components.

14. How does React manage priorities internally with the scheduler?

Answer:

React’s scheduler assigns priorities to updates: Immediate (synchronous), UserBlocking (e.g., clicks), Normal (e.g., transitions), and Low (e.g., background tasks). This enables concurrent rendering, prioritizing urgent tasks like user input over transitions.

15. What is the difference between useLayoutEffect and useInsertionEffect?

Answer:

useLayoutEffect runs synchronously after DOM mutations but before painting, ideal for measurements. useInsertionEffect runs earlier, before layout effects, and is designed for CSS-in-JS libraries to inject styles, rarely used otherwise.

16. How would you detect memory leaks in a React application?

Answer:

Detect memory leaks with browser DevTools (Performance tab, heap snapshots) or React DevTools Profiler. Common causes include unclosed subscriptions or timers in useEffect. Fix by returning cleanup functions: useEffect(() => { const timer = setInterval(...); return () => clearInterval(timer); }, []).

17. How do you handle SSR with dynamic data fetching in Next.js?

Answer:

Use getServerSideProps for runtime data fetching in Next.js: export async function getServerSideProps(context) { const data = await fetch(...); return { props: { data } }; }. Unlike getStaticProps (build-time), it fetches data per request, suitable for dynamic data.

18. How does React batch updates and what are the edge cases?

Answer:

React 18 batches state updates in event handlers, lifecycle methods, and most async contexts (e.g., setTimeout, promises). Edge cases like native event listeners may require manual batching with ReactDOM.flushSync for synchronous updates.

19. How do you measure React rendering performance?

Answer:

Measure performance with React.Profiler, Chrome DevTools (Performance tab), Lighthouse, and why-did-you-render. These identify slow renders, unnecessary re-renders, and long commit times.

20. What are the limitations of useContext for state management?

Answer:

Context is ideal for static or infrequent data (e.g., themes). Frequent updates cause all consumers to re-render, impacting performance. Optimize by memoizing context values or using libraries like Zustand for high-frequency updates.

21. How do you structure a large-scale React application?

Answer:

Structure large-scale React apps with feature-based folders, modular hooks, context for state, container/presentational component patterns, lazy loading, and domain-driven design to ensure scalability and maintainability.

22. How would you avoid re-renders in deeply nested components?

Answer:

Avoid re-renders in nested components with React.memo, useMemo for computed values, useCallback for stable function props, context selectors, or portals to isolate rendering.

23. What problems does useSyncExternalStore solve?

Answer:

useSyncExternalStore ensures consistent state reads from external stores (e.g., Redux) in concurrent mode, preventing tearing. Example: useSyncExternalStore(store.subscribe, () => store.getState()).

24. How can you make components resilient to frequent data updates?

Answer:

Make components resilient to frequent updates by debouncing data, using React.memo, useDeferredValue, or libraries like React Query/SWR for optimized fetching and caching.

25. How does React handle circular dependencies in modules?

Answer:

Circular dependencies in JavaScript modules can cause undefined imports. Detect with ESLint’s import/no-cycle rule or Webpack. Fix by restructuring code or using dynamic imports (import()).

26. What are strategies for optimizing React app bundle size?

Answer:

Optimize bundle size with code splitting, React.lazy, tree-shaking, avoiding large dependencies, and analyzing bundles with webpack-bundle-analyzer, esbuild, or Vite.

27. How do you manage component composition vs inheritance in React?

Answer:

React favors composition over inheritance. Use children, render props, and hooks to compose behavior instead of extending components like in OOP.

28. How would you handle micro-frontends in a React ecosystem?

Answer:

Implement micro-frontends with Webpack’s Module Federation or Qiankun, using dynamic imports and event-based communication. Example: exposes: { './Button': './src/Button' }, remotes: { app2: 'app2@http://...' } for runtime module sharing.

29. How do you detect unnecessary re-renders in React?

Answer:

Detect unnecessary re-renders with React DevTools Profiler or why-did-you-render. Use React.memo with custom comparison functions to prevent re-renders when props are unchanged.

30. What is the difference between state co-location and lifting state up?

Answer:

Co-location keeps state in the component using it (e.g., form input state), improving modularity. Lifting state up moves it to a parent for sharing (e.g., shared counter between siblings). Balance based on reuse and coupling needs.

31. How do you avoid waterfall loading in React applications?

Answer:

Avoid waterfall loading by fetching data in parallel with Promise.all or using frameworks like Relay/Next.js with Suspense. Example: await Promise.all([fetchA(), fetchB()]) for concurrent fetches.

32. How does React support accessibility (a11y)?

Answer:

React supports accessibility with semantic HTML, ARIA roles, keyboard navigation, and libraries like Reach UI or Radix Primitives. Test with tools like axe or Lighthouse to ensure compliance.

33. When and why should you avoid using React Context?

Answer:

Avoid using context for frequently updating data like mouse positions or animations. It causes all consumers to re-render, leading to performance bottlenecks.

34. How do you achieve feature flags in React apps?

Answer:

Implement feature flags with services like LaunchDarkly or custom toggles using Context: const FeatureContext = createContext({ newFeature: false }); {FeatureContext.newFeature && }.

35. What are some challenges of using React in highly dynamic forms?

Answer:

Challenges in dynamic forms include performance, controlled input overhead, and validation complexity. Libraries like React Hook Form or Formik reduce boilerplate and optimize re-renders.

36. How would you test components that use useEffect for data fetching?

Answer:

Test useEffect data fetching by mocking APIs with jest-fetch-mock or msw: render(); await waitFor(() => expect(screen.getByText('Data')).toBeInTheDocument());.

37. How would you memoize a component that accepts children?

Answer:

Use React.memo with a custom areEqual function for components with children, as children props are hard to compare: React.memo(Component, (prev, next) => shallowEqual(prev, next, ['children'])).

38. What are render queues and how are they handled in concurrent React?

Answer:

React’s Fiber architecture manages render queues, prioritizing updates (e.g., Immediate, Normal) via the scheduler. Concurrent mode pauses/resumes updates for responsiveness.

39. How would you migrate a legacy class-based app to hooks?

Answer:

Migrate class-based apps to hooks by replacing lifecycle methods (componentDidMountuseEffect) and state (this.stateuseState). Test incrementally, addressing pitfalls like missing useEffect dependencies.

40. How does the use of module federation work in React micro-frontends?

Answer:

Module Federation (Webpack 5) enables runtime module sharing: exposes: { './Button': './src/Button' }, remotes: { app2: 'app2@http://...' }. It supports independent deployment and shared dependencies.

41. How does state isolation affect component predictability?

Answer:

Local state isolation ensures components are independent and encapsulated, avoiding unintended side-effects from shared state and improving reusability and testability.

42. How can you implement undo/redo functionality in React?

Answer:

Implement undo/redo with a reducer:

const reducer = (state, action) => { switch (action.type) { case 'SET': return { past: [...state.past, state.present], present: action.value, future: [] }; case 'UNDO': return { past: state.past.slice(0, -1), present: state.past[state.past.length - 1], future: [state.present, ...state.future] }; } };

43. How does tree shaking work with named and default exports in React libraries?

Answer:

Tree shaking eliminates unused code in ES modules during bundling. Named exports (export { Component }) enable better dead code elimination than default exports (export default Component).

44. What is double rendering in React Strict Mode?

Answer:

React intentionally double-invokes lifecycle methods and render functions in development Strict Mode to detect unsafe side-effects. This does not happen in production.

45. How do you integrate web workers in a React app?

Answer:

Use Web Workers for heavy computations: const worker = new Worker(new URL('./worker.js', import.meta.url)); worker.postMessage(data);. Clean up in useEffect: return () => worker.terminate().

46. What are React Hooks pitfalls in large teams?

Answer:

Hooks pitfalls include incorrect dependency arrays, logic duplication, and side-effect misuse. Use eslint-plugin-react-hooks to enforce rules and extract logic into custom hooks for consistency.

47. How do you ensure type safety with React and dynamic props?

Answer:

Ensure type safety with TypeScript’s discriminated unions: type Props = { type: 'text'; value: string } | { type: 'number'; value: number }; const Component = ({ type, value }: Props) => type === 'text' ? : ;.

48. How would you create a plugin architecture in React?

Answer:

Create a plugin architecture with a PluginContext to register components: const PluginContext = createContext([]); .... Plugins render dynamically via a registry.

49. What is the role of React’s internal Fiber architecture?

Answer:

Fiber breaks rendering into units, enabling pausing, resuming, and prioritizing tasks. It improves reconciliation efficiency and supports concurrent features like transitions and Suspense.

50. How would you handle cross-tab synchronization in a React app?

Answer:

Sync tabs with BroadcastChannel, localStorage with storage events, or IndexedDB. localStorage may have latency; BroadcastChannel is faster for real-time updates.