
ReactJS is a leading library for building dynamic and responsive user interfaces, making it an essential skill for frontend and full-stack developers. Stark.ai offers curated ReactJS interview questions, hands-on challenges, and expert insights to help you stand out in your next interview.
Custom hooks in React are functions that allow you to reuse stateful logic across components. They start with the...
Pure Components (React.PureComponent or React.memo) implement shouldComponentUpdate with a shallow prop and state...
HOCs are functions that take a component and return a new component with additional props or behavior. They're used...
React.memo is a higher-order component that prevents unnecessary re-renders by memoizing the result. It performs a...
Portals (ReactDOM.createPortal) allow rendering children into a DOM node outside the parent component's hierarchy....
Dynamic imports use React.lazy() with Suspense component for code splitting. This allows components to be loaded...
Error boundaries are components that catch JavaScript errors in child component tree, log errors, and display...
Beyond props, components can communicate through context API, event emitters, state management libraries...
Reusable components should be generic, well-documented, properly typed, have clear props API, handle edge cases,...
React batches multiple state updates in the same synchronous event handler for performance. This means multiple...
Common pitfalls include: mutating state directly, not using functional updates for state depending on previous...
Cleanup functions in useEffect prevent memory leaks and stale state updates by canceling subscriptions or pending...
Split context into smaller, focused contexts, use React.memo for consumer components, implement value memoization...
State persistence can be achieved using localStorage/sessionStorage with useEffect, custom hooks for storage...
State machines provide predictable state transitions, clear visualization of possible states, prevent impossible...
Derived state is calculated from existing state/props during render. Use useMemo for expensive calculations. Avoid...
Implement undo/redo using an array of past states and current index. Use useReducer for complex state history...
State synchronization can be achieved through lifting state up, using Context API, implementing pub/sub patterns...
Use immutable update patterns with spread operator or libraries like immer. Create new object references at each...
Organize state by feature/domain, keep state as close as needed to components, use appropriate mix of local and...
Handle initial state hydration, avoid state mismatches between server and client, implement proper state...
Update UI immediately before API confirmation, maintain temporary and permanent state, implement proper rollback...
Implement WebSocket connections in useEffect, handle connection lifecycle, update state with incoming messages, and...
Use useMemo for expensive computations, implement proper cache invalidation strategies, leverage browser storage for...
useEffect runs asynchronously after render completion, while useLayoutEffect runs synchronously before browser...
getDerivedStateFromProps updates state based on prop changes. With hooks, use useEffect to observe prop changes and...
In class components, use shouldComponentUpdate or extend PureComponent. In functional components, use React.memo for...
Common pitfalls include: missing dependencies leading to stale closures, infinite loops from mutable values,...
Both can initiate async operations but require different patterns. Class methods need mounted flags for safety,...
Strict mode double-invokes certain lifecycle methods and hooks to help identify side effects. This includes...
Use componentDidMount or useLayoutEffect for DOM measurements to ensure the DOM is ready. Store measurements in...
Suspense can interrupt component mounting and trigger fallback rendering. Effects may be delayed or re-run. Consider...
Avoid state updates in render phase. Use componentDidMount/Update or effects for async state updates. Consider...
Implement preloading in componentDidMount or useEffect with empty dependency array. Consider using Suspense for data...
Establish connections in componentDidMount or useEffect, handle reconnection logic in componentDidUpdate or with...
Implement storage updates in effects or lifecycle methods, handle rehydration on mount, and clean up on unmount....
Split effects by concern, manage dependencies independently, consider effect ordering, and implement proper cleanup...
useImperativeHandle customizes the instance value exposed to parent components when using ref. It allows you to...
Use useMemo for expensive calculations and useCallback for function props passed to optimized child components....
useLayoutEffect fires synchronously after DOM mutations but before browser paint. Use it when you need to make DOM...
Create custom hooks that encapsulate the shared logic, state, and side effects. Ensure hooks are generic enough for...
useDebugValue adds a label to custom hooks in React DevTools. Use it to display custom hook values for debugging....
Common pitfalls include: missing dependencies leading to stale closures, unnecessary dependencies causing excess...
Use useCallback and useRef to create a debounced function that delays execution. Clear previous timeout in cleanup....
Since error boundaries must be class components, create a custom hook that works with an error boundary component....
Use useReducer to manage state history array and current index. Implement actions for undo, redo, and new states....
Create a custom hook that establishes connection in useEffect, handles message events, and cleans up on unmount....
Create custom hooks for managing auth state, token storage, and user session. Handle login, logout, token refresh,...
Create a custom hook that manages scroll position, loading state, and data fetching. Use intersection observer or...
Create a custom hook that manages keyboard event listeners using useEffect. Handle key combinations, prevent default...
Use useReducer with a state machine configuration. Define states, transitions, and actions. Consider using libraries...
Render props are functions passed as props that return React elements. They enable sharing behavior between...
Use PropTypes.shape() for objects, PropTypes.arrayOf() for arrays, and custom validators for complex validation....
HOCs are functions that take a component and return an enhanced component. They can manipulate props, add new props,...
Use React.memo for functional components or PureComponent for class components to prevent unnecessary re-renders....
Define interfaces or types for props: interface Props { name: string; age?: number; }. Use them in component...
Pass loading states and error states as props along with data. Use promises or async/await in parent components....
Compound components are related components that work together sharing implicit state. They often use Context...
Use useEffect to watch for prop changes and trigger animations. Consider using libraries like Framer Motion. Handle...
Prefer computing values during render instead of storing in state. Use useMemo for expensive calculations. If state...
Remove PropTypes in production builds for performance. Implement error boundaries for runtime errors. Consider...
Avoid circular prop passing. Restructure component hierarchy. Consider using Context or state management. Break...
Use dynamic imports based on props. Implement proper loading states. Handle errors during chunk loading. Consider...
Never expose sensitive data in client-side props. Use proper authentication and authorization. Consider encryption...
Use async/await or promises, handle loading and error states, prevent memory leaks with cleanup, consider...
Custom events can be created using new CustomEvent() and dispatched using dispatchEvent(). In React, prefer prop...
Use HTML5 drag and drop events (onDragStart, onDrop, etc.). Implement dataTransfer for data passing. Consider using...
Handle touchstart, touchmove, touchend events. Consider touch gestures, preventing scroll during touch interactions,...
Use custom hooks or utility functions for debounce/throttle. Consider cleanup on unmount. Example: const...
Use event.stopPropagation() to prevent bubbling, organize handlers hierarchically, consider event delegation, and...
Set up WebSocket connections in useEffect, handle connection events, implement proper cleanup, and manage message...
Create hooks that encapsulate event logic, handle setup/cleanup, manage event state, and provide simple interfaces....
Use throttling or requestAnimationFrame for scroll handlers, consider intersection observer for scroll detection,...
Handle animation start/end events, manage animation state, implement cleanup for interrupted animations, and...
Handle play, pause, loadeddata, error events for audio/video elements. Implement proper cleanup, manage playback...
Events bubble up through React's virtual DOM hierarchy regardless of portal placement. Consider event propagation,...
Handle hydration mismatches, avoid accessing window/document during SSR, implement proper event attachment after...
React 17+ removed event pooling, but understanding includes: using event.persist() for async access in older...
Create custom hooks for intersection observer, handle observer setup/cleanup, manage intersection state, and...
File inputs are typically uncontrolled. Access files through e.target.files in onChange handler. Use FileReader for...
Consider debouncing for frequent updates, batch state updates when possible, use memoization for expensive...
Create components that accept value and onChange props, maintain internal state if needed, properly handle user...
Use nested objects in state, implement proper update logic for nested fields, consider using libraries for complex...
Maintain overall form state across steps, validate each step independently, handle navigation between steps, persist...
Use localStorage/sessionStorage to save form state, implement auto-save functionality, handle form recovery on page...
Maintain array of fields in state, implement add/remove field functionality, handle validation for dynamic fields....
Implement debounced validation calls, handle loading states, cache validation results when appropriate. Consider...
Use FormData for file uploads, handle upload progress, implement proper error handling and retry logic. Consider...
Implement proper label and error message translations, handle different date/number formats, consider right-to-left...
Implement debounced save function, handle save states and errors, provide user feedback. Consider conflict...
Implement proper actions and reducers for form state, handle form namespacing, consider performance implications....
Implement virtualization for large lists, optimize validation runs, use proper memoization. Consider chunking large...
Handle controlled component behavior, implement proper keyboard navigation, manage dropdown state and positioning....
Implement exponential backoff, handle different error types, maintain submission state. Consider user feedback...
Implement CSRF protection, validate inputs server-side, handle sensitive data properly, prevent XSS attacks....
Handle initial form state hydration, prevent flash of uncontrolled inputs, implement proper client-side validation...
Use React.lazy and Suspense with React Router to load components dynamically. Implement per-route code splitting for...
Use React Transition Group with React Router. Implement enter/exit animations, handle route-based transitions, and...
Use StaticRouter instead of BrowserRouter for SSR. Handle location context, match routes on server, and manage data...
Use route configuration and current location to generate breadcrumbs. Handle dynamic segments, maintain breadcrumb...
Implement higher-order components or custom Route components for protection. Handle authentication, authorization,...
Implement custom scroll behavior using useEffect. Handle scroll position per route, manage scroll restoration, and...
Implement React.lazy with prefetching strategies. Handle component preloading, manage loading states, and optimize...
MemoryRouter keeps history in memory (not in URL). Useful for testing and non-browser environments. Maintains...
Use MemoryRouter for testing, mock route matches and history. Test navigation, protected routes, and route...
Use virtualization (react-window or react-virtualized) to render only visible items. Implement windowing,...
Context updates can cause all consuming components to re-render. Optimize by splitting context, using memoization,...
Implement route-based code splitting, use proper caching strategies, optimize route matching, and implement proper...
Use controlled components judiciously, implement debouncing for frequent updates, optimize validation timing, and...
Choose appropriate state management solution, normalize state structure, implement proper selectors, and avoid...
Web Workers handle CPU-intensive tasks off the main thread. Implement for heavy computations, data processing, and...
Use CSS transforms and opacity, implement requestAnimationFrame, avoid layout thrashing, and consider using Web...
Use React DevTools Profiler, implement performance metrics collection, monitor key user interactions, and track core...
ErrorBoundaries prevent entire app crashes but can impact performance if overused. Implement strategically, handle...
Implement proper data fetching strategies, optimize component rendering, implement caching, and handle hydration...
Choose appropriate data structures, implement proper normalization, use immutable data patterns, and optimize state...
Context triggers re-renders in all consuming components when its value changes. Optimize by splitting contexts,...
Use React.memo on consuming components, memoize context value with useMemo, implement proper value comparison....
Context selectors help consume specific parts of context to prevent unnecessary re-renders. Implement using custom...
Use useReducer with Context for complex state management, implement proper action dispatching, handle state updates...
Combine Context with useEffect for async operations, handle loading and error states, implement proper state...
Compose multiple contexts to separate concerns, improve maintainability, and optimize performance. Use when...
Overusing context, unnecessary re-renders, improper value memoization, context hell (too many nested providers)....
Use context for form state management, implement proper validation, handle field updates efficiently. Consider form...
Define proper types for context values, use generic types when needed, implement type checking. Consider type safety...
Implement storage synchronization, handle hydration, manage persistence lifecycle. Consider storage options and...
Implement proper cleanup in effects, handle unmount scenarios, manage resource disposal. Consider memory leaks and...
Create contexts dynamically, handle context creation lifecycle, manage dynamic providers. Consider performance and...
Implement retry logic, state reset mechanisms, fallback UI, and proper error clearing. Consider user experience and...
Use try-catch in effects, implement error states, handle cleanup properly, consider custom hooks for error handling....
Implement error reducers, handle async action errors, provide error states in store, consider middleware for error...
Place boundaries strategically to isolate failures, consider component hierarchy, implement granular error handling....
Use Error Boundaries with Suspense, handle loading errors, implement fallback UI, manage timeout scenarios. Consider...
Implement error handling logic in HOCs, wrap components with error boundaries, handle prop validation errors....
Use error boundaries around portals, handle portal-specific errors, manage cleanup on errors. Consider modal and...
Provide fallback functionality, implement feature detection, handle browser compatibility issues. Consider...
Implement SSR-specific error handling, manage hydration errors, handle state reconciliation issues. Consider...
Implement proper cleanup in useEffect, handle component unmounting, manage resource disposal. Consider async...
Implement error tracking services, collect error metrics, analyze error patterns, set up alerts. Consider privacy...
Integrate error tracking services, collect relevant error data, implement proper error categorization. Consider...
Test error boundaries, simulate different error conditions, verify error recovery, implement comprehensive test...
Use @testing-library/react-hooks with renderHook, test different scenarios and state changes, verify hook behavior...
Provide test store using Provider, mock store state and actions, test component integration with Redux. Consider...
Test component interactions, data flow between components, state management integration. Focus on user workflows and...
Simulate errors to test boundary behavior, verify fallback UI rendering, test error recovery. Consider different...
Mock external dependencies, API calls, and complex functionality. Use jest.mock() appropriately, maintain mock...
Use jest-axe for accessibility testing, verify ARIA attributes, test keyboard navigation. Consider screen reader...
Test animation triggers and completion, verify state changes during transitions, mock timers appropriately. Consider...
Test render counts, verify memoization effectiveness, check optimization implementations. Consider performance...
Mock File API, test upload handlers, verify file validation and processing. Consider different file types and error...
Use Cypress or Playwright for end-to-end testing, test complete user flows, verify application integration. Consider...
Test portal rendering and content, verify portal functionality and events. Consider DOM structure and cleanup.
Test loading states, verify component lazy loading, check suspense fallbacks. Consider network conditions and timing.
Test state updates and transitions, verify state synchronization, check state persistence. Consider complex state...
Use tools like Percy or Chromatic, compare visual changes, maintain visual consistency. Consider different viewport...
CSS-in-JS can impact runtime performance, CSS Modules have build-time overhead, inline styles prevent browser...
Use proper type definitions for styled components, implement theme typing, handle prop types for styled components....
Use CSS Modules for scoping, implement proper class naming conventions, manage specificity hierarchy. Consider...
Use CSS logical properties, implement directional styles, handle bidirectional text properly. Consider cultural...
Implement page transition animations, handle route-based styles, manage transition states. Consider performance and...
Use style props for component customization, implement consistent prop interfaces, handle style composition....
Implement critical CSS, handle code splitting, optimize load performance. Consider caching strategies and resource hints.
Handle style extraction, implement proper hydration, manage style injection. Consider performance and flash of...
Implement data-driven styles, handle dynamic classes and properties, manage style updates. Consider performance and...
Define and manage design tokens, implement token-based styling system, handle theme variations. Consider...
Test style rendering, verify theme integration, check dynamic styles. Consider snapshot testing and visual...
Use React.memo for expensive components, implement proper key usage, avoid unnecessary re-renders, use proper...
Implement proper data fetching patterns, handle loading and error states, implement caching strategies, maintain...
Follow ARIA guidelines, implement proper keyboard navigation, maintain proper heading hierarchy, provide proper alt...
Use TypeScript or PropTypes, implement proper type definitions, maintain type consistency, handle type edge cases,...
Use context appropriately for global state, implement proper provider organization, optimize context updates, avoid...
Implement proper component composition, create reusable hooks, maintain proper abstraction levels, implement proper...
Prevent XSS attacks, handle sensitive data properly, implement proper authentication/authorization, validate inputs,...
Implement proper performance metrics, use React DevTools effectively, monitor render performance, track user...
Implement proper lazy loading, use dynamic imports effectively, handle loading states, optimize bundle size, and...
Implement proper i18n solution, handle translations effectively, manage locale changes, consider RTL support, and...
Implement proper storage strategies, handle state rehydration, manage persistence lifecycle, consider offline...
Implement proper fallbacks, handle feature detection, maintain core functionality, consider browser support, and...
Implement proper build process, optimize asset delivery, handle environment variables, implement proper CI/CD, and...
Manage tokens securely, handle token refresh, implement interceptors for requests, manage auth state. Consider...
Use caching libraries (React Query, SWR), implement local storage caching, handle cache invalidation, manage cache...
Implement WebSocket connections, handle Socket.IO integration, manage real-time state updates, handle connection...
Implement request debouncing/throttling, batch requests when possible, optimize payload size, use proper caching...
Implement service workers, handle offline storage, manage sync queues, handle conflict resolution. Consider...
Update UI immediately before API confirmation, handle rollback on failure, manage temporary state, implement proper...
Implement request queuing, handle rate limit errors, manage retry strategies, provide user feedback. Consider...
Implement proper authentication/authorization, handle CORS, prevent XSS attacks, manage sensitive data. Consider...
Handle sequential requests, manage request priority, implement queue processing logic. Consider error handling and...
Track request times, monitor error rates, implement performance metrics, analyze bottlenecks. Consider monitoring...
Use Apollo Client or other GraphQL clients, manage queries and mutations, handle caching, implement proper error...
Implement request combining, manage batch processing, handle response correlation, optimize network usage. Consider...
Implement local storage caching, handle state rehydration, manage persistence lifecycle. Consider storage strategies...
Custom hooks in React are functions that allow you to reuse stateful logic across components. They start with the word `use` and can encapsulate complex logic using existing React hooks like `useState` and `useEffect`.
Pure Components (React.PureComponent or React.memo) implement shouldComponentUpdate with a shallow prop and state comparison. They're used to optimize performance by preventing unnecessary re-renders when props or state haven't changed significantly.
HOCs are functions that take a component and return a new component with additional props or behavior. They're used for code reuse, adding additional functionality like data fetching, authentication, or logging. HOCs follow the pattern: const EnhancedComponent = higherOrderComponent(WrappedComponent).
React.memo is a higher-order component that prevents unnecessary re-renders by memoizing the result. It performs a shallow comparison of props and only re-renders if props have changed. Useful for performance optimization in components with expensive renders.
Portals (ReactDOM.createPortal) allow rendering children into a DOM node outside the parent component's hierarchy. Useful for modals, tooltips, or floating elements that need to break out of parent container limitations while maintaining React context.
Dynamic imports use React.lazy() with Suspense component for code splitting. This allows components to be loaded only when needed: const DynamicComponent = React.lazy(() => import('./Component')). Suspense provides fallback content during loading.
Error boundaries are components that catch JavaScript errors in child component tree, log errors, and display fallback UI. They must be class components using componentDidCatch or static getDerivedStateFromError. They don't catch errors in event handlers or async code.
Beyond props, components can communicate through context API, event emitters, state management libraries (Redux/MobX), or custom hooks. Choice depends on scope of communication, app size, and performance requirements.
Reusable components should be generic, well-documented, properly typed, have clear props API, handle edge cases, maintain single responsibility, and be tested thoroughly. Consider composition, prop drilling, and state management needs.
React batches multiple state updates in the same synchronous event handler for performance. This means multiple setState calls may be processed in a single re-render. In async operations, use functional updates (prevState => newState) to ensure correct state updates.
Common pitfalls include: mutating state directly, not using functional updates for state depending on previous value, initializing with expensive operations without lazy initialization, and not considering batching behavior in async operations.
Cleanup functions in useEffect prevent memory leaks and stale state updates by canceling subscriptions or pending operations when component unmounts or dependencies change. Return a cleanup function from useEffect for proper resource management.
Split context into smaller, focused contexts, use React.memo for consumer components, implement value memoization with useMemo, and consider using context selectors. Avoid putting frequently changing values in context.
State persistence can be achieved using localStorage/sessionStorage with useEffect, custom hooks for storage synchronization, or state management libraries with persistence middleware. Consider serialization and hydration strategies.
State machines provide predictable state transitions, clear visualization of possible states, prevent impossible states, and make complex workflows manageable. Libraries like XState help implement state machines in React.
Derived state is calculated from existing state/props during render. Use useMemo for expensive calculations. Avoid storing derived values in state; compute them during render to prevent state synchronization issues.
Implement undo/redo using an array of past states and current index. Use useReducer for complex state history management. Consider memory usage and performance implications for large state objects.
State synchronization can be achieved through lifting state up, using Context API, implementing pub/sub patterns with custom events, or using state management libraries. Consider performance and complexity trade-offs.
Use immutable update patterns with spread operator or libraries like immer. Create new object references at each level of nesting. Consider flattening state structure when possible to simplify updates.
Organize state by feature/domain, keep state as close as needed to components, use appropriate mix of local and global state, implement proper state normalization, and document state shape and update patterns.
Handle initial state hydration, avoid state mismatches between server and client, implement proper state serialization, and consider using state management solutions that support SSR like Redux or Zustand.
Update UI immediately before API confirmation, maintain temporary and permanent state, implement proper rollback mechanisms for failures, and handle race conditions in concurrent updates.
Implement WebSocket connections in useEffect, handle connection lifecycle, update state with incoming messages, and implement proper cleanup. Consider using libraries like Socket.io or custom hooks for WebSocket state.
Use useMemo for expensive computations, implement proper cache invalidation strategies, leverage browser storage for persistence, and consider using caching libraries like react-query for server state.
useEffect runs asynchronously after render completion, while useLayoutEffect runs synchronously before browser paint. useLayoutEffect is used for DOM measurements and mutations that need to be synchronized with rendering to prevent visual flicker.
getDerivedStateFromProps updates state based on prop changes. With hooks, use useEffect to observe prop changes and update state accordingly, but consider if derived state is really needed versus computing values during render.
In class components, use shouldComponentUpdate or extend PureComponent. In functional components, use React.memo for props comparison and useMemo/useCallback to prevent unnecessary re-renders of child components.
Common pitfalls include: missing dependencies leading to stale closures, infinite loops from mutable values, unnecessary re-renders from object/array dependencies, and over-dependency on external values. Use ESLint rules and proper dependency management.
Both can initiate async operations but require different patterns. Class methods need mounted flags for safety, while hooks can use cleanup functions to cancel pending operations. Consider race conditions and component unmounting.
Strict mode double-invokes certain lifecycle methods and hooks to help identify side effects. This includes constructor, render, and useEffect. Use it to catch lifecycle-related bugs and ensure proper cleanup implementation.
Use componentDidMount or useLayoutEffect for DOM measurements to ensure the DOM is ready. Store measurements in state or refs. Consider resize observers and window event listeners with proper cleanup.
Suspense can interrupt component mounting and trigger fallback rendering. Effects may be delayed or re-run. Consider the implications for data fetching, lazy loading, and error handling in lifecycle methods and effects.
Avoid state updates in render phase. Use componentDidMount/Update or effects for async state updates. Consider batching updates and proper error handling. Be aware of setState's asynchronous nature.
Implement preloading in componentDidMount or useEffect with empty dependency array. Consider using Suspense for data fetching and lazy loading. Handle cleanup for abandoned preload requests.
Establish connections in componentDidMount or useEffect, handle reconnection logic in componentDidUpdate or with dependencies, and clean up in componentWillUnmount or effect cleanup. Consider connection state management.
Implement storage updates in effects or lifecycle methods, handle rehydration on mount, and clean up on unmount. Consider using localStorage/sessionStorage with proper serialization and cleanup.
Split effects by concern, manage dependencies independently, consider effect ordering, and implement proper cleanup for each effect. Use custom hooks to encapsulate related effect logic.
useImperativeHandle customizes the instance value exposed to parent components when using ref. It allows you to control which values and methods are accessible via the ref, enabling better encapsulation of component internals.
Use useMemo for expensive calculations and useCallback for function props passed to optimized child components. Ensure dependency arrays are properly configured. Only use when there's a measurable performance benefit to avoid unnecessary complexity.
useLayoutEffect fires synchronously after DOM mutations but before browser paint. Use it when you need to make DOM measurements or mutations that should be synchronized with rendering to prevent visual flickers.
Create custom hooks that encapsulate the shared logic, state, and side effects. Ensure hooks are generic enough for reuse but specific enough to be useful. Consider composition of multiple hooks for complex logic.
useDebugValue adds a label to custom hooks in React DevTools. Use it to display custom hook values for debugging. Consider using the format function parameter to defer expensive formatting until the hook is inspected.
Common pitfalls include: missing dependencies leading to stale closures, unnecessary dependencies causing excess renders, object/array dependencies causing infinite loops, and circular dependencies. Use ESLint rules and proper dependency management.
Use useCallback and useRef to create a debounced function that delays execution. Clear previous timeout in cleanup. Consider returning both debounced and immediate execution functions.
Since error boundaries must be class components, create a custom hook that works with an error boundary component. Use try-catch in event handlers and effects. Consider implementing retry logic and error logging.
Use useReducer to manage state history array and current index. Implement actions for undo, redo, and new states. Consider memory usage and limiting history size for large state objects.
Create a custom hook that establishes connection in useEffect, handles message events, and cleans up on unmount. Consider reconnection logic, message queuing, and connection status management.
Create custom hooks for managing auth state, token storage, and user session. Handle login, logout, token refresh, and protected routes. Consider persistent sessions and security implications.
Create a custom hook that manages scroll position, loading state, and data fetching. Use intersection observer or scroll events. Consider data caching, cleanup, and performance optimization.
Create a custom hook that manages keyboard event listeners using useEffect. Handle key combinations, prevent default behaviors, and clean up listeners. Consider focus management and accessibility.
Use useReducer with a state machine configuration. Define states, transitions, and actions. Consider using libraries like XState. Handle side effects and state persistence.
Render props are functions passed as props that return React elements. They enable sharing behavior between components: <DataProvider render={data => <Display data={data} />}. This pattern allows for flexible component composition.
Use PropTypes.shape() for objects, PropTypes.arrayOf() for arrays, and custom validators for complex validation. Example: PropTypes.shape({ id: PropTypes.number, items: PropTypes.arrayOf(PropTypes.object) }).
HOCs are functions that take a component and return an enhanced component. They can manipulate props, add new props, or handle prop-related logic. Important to properly forward props: {...props} to avoid prop isolation.
Use React.memo for functional components or PureComponent for class components to prevent unnecessary re-renders. Implement shouldComponentUpdate for custom comparison. Consider prop structure and reference equality.
Define interfaces or types for props: interface Props { name: string; age?: number; }. Use them in component definitions: const Component: React.FC<Props> = ({name, age}) => {}. TypeScript provides compile-time type safety.
Pass loading states and error states as props along with data. Use promises or async/await in parent components. Consider implementing loading skeletons or error boundaries. Handle race conditions in updates.
Compound components are related components that work together sharing implicit state. They often use Context internally while exposing a declarative API through props. Example: <Select><Option value='1'>One</Option></Select>.
Use useEffect to watch for prop changes and trigger animations. Consider using libraries like Framer Motion. Handle cleanup of animation timeouts. Manage transition states properly.
Prefer computing values during render instead of storing in state. Use useMemo for expensive calculations. If state is needed, update it in useEffect. Consider getDerivedStateFromProps in class components.
Remove PropTypes in production builds for performance. Implement error boundaries for runtime errors. Consider logging prop validation errors. Use TypeScript for compile-time validation.
Avoid circular prop passing. Restructure component hierarchy. Consider using Context or state management. Break circular dependencies through component composition.
Use dynamic imports based on props. Implement proper loading states. Handle errors during chunk loading. Consider performance implications and bundle size.
Never expose sensitive data in client-side props. Use proper authentication and authorization. Consider encryption for necessary client-side data. Implement proper cleanup.
Use async/await or promises, handle loading and error states, prevent memory leaks with cleanup, consider debouncing/throttling, and handle component unmounting. Example: async handleClick() { try { await apiCall() } catch (error) { handleError() } }
Custom events can be created using new CustomEvent() and dispatched using dispatchEvent(). In React, prefer prop callbacks or event emitters for component communication. Handle cleanup for custom event listeners.
Use HTML5 drag and drop events (onDragStart, onDrop, etc.). Implement dataTransfer for data passing. Consider using react-dnd or similar libraries for complex cases. Handle drag preview and drop zones.
Handle touchstart, touchmove, touchend events. Consider touch gestures, preventing scroll during touch interactions, and handling multi-touch. Test on various devices and implement fallbacks for desktop.
Use custom hooks or utility functions for debounce/throttle. Consider cleanup on unmount. Example: const debouncedHandler = useDebounce(handler, delay). Handle edge cases and cancellation.
Use event.stopPropagation() to prevent bubbling, organize handlers hierarchically, consider event delegation, and handle event order carefully. Avoid deeply nested event handling logic.
Set up WebSocket connections in useEffect, handle connection events, implement proper cleanup, and manage message events. Consider reconnection logic and error handling.
Create hooks that encapsulate event logic, handle setup/cleanup, manage event state, and provide simple interfaces. Example: useEventListener hook for declarative event handling.
Use throttling or requestAnimationFrame for scroll handlers, consider intersection observer for scroll detection, and implement cleanup properly. Handle scroll position restoration and virtual scrolling.
Handle animation start/end events, manage animation state, implement cleanup for interrupted animations, and consider performance. Use requestAnimationFrame for smooth animations.
Handle play, pause, loadeddata, error events for audio/video elements. Implement proper cleanup, manage playback state, and handle loading/buffering. Consider mobile device considerations.
Events bubble up through React's virtual DOM hierarchy regardless of portal placement. Consider event propagation, handle cleanup properly, and manage portal lifecycle.
Handle hydration mismatches, avoid accessing window/document during SSR, implement proper event attachment after hydration, and consider initial state handling.
React 17+ removed event pooling, but understanding includes: using event.persist() for async access in older versions, handling synthetic event limitations, and managing event object lifecycle.
Create custom hooks for intersection observer, handle observer setup/cleanup, manage intersection state, and implement proper threshold configuration. Use for infinite scroll or lazy loading.
File inputs are typically uncontrolled. Access files through e.target.files in onChange handler. Use FileReader for preview, FormData for upload. Handle multiple files, validation, and upload progress. Consider drag-and-drop functionality.
Consider debouncing for frequent updates, batch state updates when possible, use memoization for expensive validations, optimize re-renders with proper component structure. Balance real-time validation with performance.
Create components that accept value and onChange props, maintain internal state if needed, properly handle user interactions, and implement proper event handling. Ensure compatibility with form libraries and validation.
Use nested objects in state, implement proper update logic for nested fields, consider using libraries for complex state updates. Example: setState({...form, address: {...form.address, street: value}}). Handle array fields appropriately.
Maintain overall form state across steps, validate each step independently, handle navigation between steps, persist partial data. Consider using reducers for complex state management and proper error handling.
Use localStorage/sessionStorage to save form state, implement auto-save functionality, handle form recovery on page reload. Consider cleaning up saved data and handling version conflicts.
Maintain array of fields in state, implement add/remove field functionality, handle validation for dynamic fields. Consider performance implications and proper state updates for array manipulations.
Implement debounced validation calls, handle loading states, cache validation results when appropriate. Consider race conditions and cancellation of pending validation requests.
Use FormData for file uploads, handle upload progress, implement proper error handling and retry logic. Consider chunked uploads for large files and proper cleanup of file references.
Implement proper label and error message translations, handle different date/number formats, consider right-to-left languages. Use proper localization libraries and handle cultural differences.
Implement debounced save function, handle save states and errors, provide user feedback. Consider conflict resolution and offline capabilities. Handle cleanup of autosave timers.
Implement proper actions and reducers for form state, handle form namespacing, consider performance implications. Balance local vs global state for form data.
Implement virtualization for large lists, optimize validation runs, use proper memoization. Consider chunking large forms and implementing progressive loading.
Handle controlled component behavior, implement proper keyboard navigation, manage dropdown state and positioning. Consider accessibility and mobile device support.
Implement exponential backoff, handle different error types, maintain submission state. Consider user feedback during retries and proper cleanup of retry attempts.
Implement CSRF protection, validate inputs server-side, handle sensitive data properly, prevent XSS attacks. Consider authentication state and proper permissions checking.
Handle initial form state hydration, prevent flash of uncontrolled inputs, implement proper client-side validation initialization. Consider SEO implications and performance optimization.
Use React.lazy and Suspense with React Router to load components dynamically. Implement per-route code splitting for better performance and smaller initial bundle size.
Use React Transition Group with React Router. Implement enter/exit animations, handle route-based transitions, and manage transition states properly.
Use StaticRouter instead of BrowserRouter for SSR. Handle location context, match routes on server, and manage data loading. Consider hydration and state management.
Use route configuration and current location to generate breadcrumbs. Handle dynamic segments, maintain breadcrumb state, and implement proper navigation.
Implement higher-order components or custom Route components for protection. Handle authentication, authorization, and redirect flows appropriately.
Implement custom scroll behavior using useEffect. Handle scroll position per route, manage scroll restoration, and implement smooth scrolling.
Implement React.lazy with prefetching strategies. Handle component preloading, manage loading states, and optimize performance.
MemoryRouter keeps history in memory (not in URL). Useful for testing and non-browser environments. Maintains routing state without URL changes.
Use MemoryRouter for testing, mock route matches and history. Test navigation, protected routes, and route parameters. Implement comprehensive test cases.
Use virtualization (react-window or react-virtualized) to render only visible items. Implement windowing, pagination, or infinite scroll. Consider key optimization and memoization for list items.
Context updates can cause all consuming components to re-render. Optimize by splitting context, using memoization, and implementing proper value comparison. Consider alternative state management for frequent updates.
Implement route-based code splitting, use proper caching strategies, optimize route matching, and implement proper loading states. Consider preloading routes and route-level data fetching.
Use controlled components judiciously, implement debouncing for frequent updates, optimize validation timing, and consider uncontrolled components for simple forms. Handle large form state efficiently.
Choose appropriate state management solution, normalize state structure, implement proper selectors, and avoid unnecessary state updates. Consider using immutable data structures.
Web Workers handle CPU-intensive tasks off the main thread. Implement for heavy computations, data processing, and background tasks. Consider using worker-loader or similar tools.
Use CSS transforms and opacity, implement requestAnimationFrame, avoid layout thrashing, and consider using Web Animations API. Optimize animation frame rate and smooth transitions.
Use React DevTools Profiler, implement performance metrics collection, monitor key user interactions, and track core web vitals. Consider using performance monitoring tools and analytics.
ErrorBoundaries prevent entire app crashes but can impact performance if overused. Implement strategically, handle errors appropriately, and consider performance implications of error tracking.
Implement proper data fetching strategies, optimize component rendering, implement caching, and handle hydration efficiently. Consider streaming SSR and selective hydration.
Choose appropriate data structures, implement proper normalization, use immutable data patterns, and optimize state shape. Consider performance implications of deep nesting.
Context triggers re-renders in all consuming components when its value changes. Optimize by splitting contexts, using memoization, and considering component structure. Avoid putting frequently changing values in context.
Use React.memo on consuming components, memoize context value with useMemo, implement proper value comparison. Consider component structure and update patterns.
Context selectors help consume specific parts of context to prevent unnecessary re-renders. Implement using custom hooks, memoization, and proper state structure.
Use useReducer with Context for complex state management, implement proper action dispatching, handle state updates efficiently. Similar to Redux pattern but lighter weight.
Combine Context with useEffect for async operations, handle loading and error states, implement proper state updates. Consider async patterns and error boundaries.
Compose multiple contexts to separate concerns, improve maintainability, and optimize performance. Use when different parts of the app need different subsets of global state.
Overusing context, unnecessary re-renders, improper value memoization, context hell (too many nested providers). Consider alternatives and proper architecture.
Use context for form state management, implement proper validation, handle field updates efficiently. Consider form complexity and performance requirements.
Define proper types for context values, use generic types when needed, implement type checking. Consider type safety and proper interface definitions.
Implement storage synchronization, handle hydration, manage persistence lifecycle. Consider storage options and state reconciliation.
Implement proper cleanup in effects, handle unmount scenarios, manage resource disposal. Consider memory leaks and cleanup timing.
Create contexts dynamically, handle context creation lifecycle, manage dynamic providers. Consider performance and maintenance implications.
Implement retry logic, state reset mechanisms, fallback UI, and proper error clearing. Consider user experience and recovery workflows.
Use try-catch in effects, implement error states, handle cleanup properly, consider custom hooks for error handling. Cannot use error boundaries directly in hooks.
Implement error reducers, handle async action errors, provide error states in store, consider middleware for error handling. Handle global vs local error states.
Place boundaries strategically to isolate failures, consider component hierarchy, implement granular error handling. Balance between too many and too few boundaries.
Use Error Boundaries with Suspense, handle loading errors, implement fallback UI, manage timeout scenarios. Consider data fetching errors.
Implement error handling logic in HOCs, wrap components with error boundaries, handle prop validation errors. Consider composition of error handling HOCs.
Use error boundaries around portals, handle portal-specific errors, manage cleanup on errors. Consider modal and overlay error scenarios.
Provide fallback functionality, implement feature detection, handle browser compatibility issues. Consider progressive enhancement approaches.
Implement SSR-specific error handling, manage hydration errors, handle state reconciliation issues. Consider client-server error differences.
Implement proper cleanup in useEffect, handle component unmounting, manage resource disposal. Consider async operation cancellation.
Implement error tracking services, collect error metrics, analyze error patterns, set up alerts. Consider privacy and performance implications.
Integrate error tracking services, collect relevant error data, implement proper error categorization. Consider privacy and compliance requirements.
Test error boundaries, simulate different error conditions, verify error recovery, implement comprehensive test cases. Consider edge cases and error combinations.
Use @testing-library/react-hooks with renderHook, test different scenarios and state changes, verify hook behavior and side effects. Consider proper cleanup and isolation.
Provide test store using Provider, mock store state and actions, test component integration with Redux. Consider proper store setup and cleanup.
Test component interactions, data flow between components, state management integration. Focus on user workflows and feature completeness. Consider proper test isolation.
Simulate errors to test boundary behavior, verify fallback UI rendering, test error recovery. Consider different error scenarios and component hierarchy.
Mock external dependencies, API calls, and complex functionality. Use jest.mock() appropriately, maintain mock clarity. Consider partial mocking and mock cleanup.
Use jest-axe for accessibility testing, verify ARIA attributes, test keyboard navigation. Consider screen reader compatibility and accessibility guidelines.
Test animation triggers and completion, verify state changes during transitions, mock timers appropriately. Consider animation cleanup and timing issues.
Test render counts, verify memoization effectiveness, check optimization implementations. Consider performance measurement and monitoring in tests.
Mock File API, test upload handlers, verify file validation and processing. Consider different file types and error scenarios.
Use Cypress or Playwright for end-to-end testing, test complete user flows, verify application integration. Consider test stability and maintenance.
Test portal rendering and content, verify portal functionality and events. Consider DOM structure and cleanup.
Test loading states, verify component lazy loading, check suspense fallbacks. Consider network conditions and timing.
Test state updates and transitions, verify state synchronization, check state persistence. Consider complex state scenarios and side effects.
Use tools like Percy or Chromatic, compare visual changes, maintain visual consistency. Consider different viewport sizes and browser compatibility.
CSS-in-JS can impact runtime performance, CSS Modules have build-time overhead, inline styles prevent browser optimizations. Consider bundle size, runtime performance, and caching strategies.
Use proper type definitions for styled components, implement theme typing, handle prop types for styled components. Consider type safety and proper inference.
Use CSS Modules for scoping, implement proper class naming conventions, manage specificity hierarchy. Consider cascade and inheritance implications.
Use CSS logical properties, implement directional styles, handle bidirectional text properly. Consider cultural differences and layout implications.
Implement page transition animations, handle route-based styles, manage transition states. Consider performance and user experience.
Use style props for component customization, implement consistent prop interfaces, handle style composition. Consider type safety and documentation.
Implement critical CSS, handle code splitting, optimize load performance. Consider caching strategies and resource hints.
Handle style extraction, implement proper hydration, manage style injection. Consider performance and flash of unstyled content.
Implement data-driven styles, handle dynamic classes and properties, manage style updates. Consider performance and maintainability.
Define and manage design tokens, implement token-based styling system, handle theme variations. Consider maintainability and consistency.
Test style rendering, verify theme integration, check dynamic styles. Consider snapshot testing and visual regression testing.
Use React.memo for expensive components, implement proper key usage, avoid unnecessary re-renders, use proper dependency arrays in hooks, lazy load components, and implement code splitting.
Implement proper data fetching patterns, handle loading and error states, implement caching strategies, maintain proper separation of concerns, and consider API state management.
Follow ARIA guidelines, implement proper keyboard navigation, maintain proper heading hierarchy, provide proper alt texts, and implement proper focus management.
Use TypeScript or PropTypes, implement proper type definitions, maintain type consistency, handle type edge cases, and consider type inference optimization.
Use context appropriately for global state, implement proper provider organization, optimize context updates, avoid context overuse, and consider performance implications.
Implement proper component composition, create reusable hooks, maintain proper abstraction levels, implement proper HOC patterns, and consider code sharing strategies.
Prevent XSS attacks, handle sensitive data properly, implement proper authentication/authorization, validate inputs, and consider security implications in data handling.
Implement proper performance metrics, use React DevTools effectively, monitor render performance, track user interactions, and consider performance optimization strategies.
Implement proper lazy loading, use dynamic imports effectively, handle loading states, optimize bundle size, and consider code splitting strategies.
Implement proper i18n solution, handle translations effectively, manage locale changes, consider RTL support, and implement proper internationalization patterns.
Implement proper storage strategies, handle state rehydration, manage persistence lifecycle, consider offline support, and implement proper persistence patterns.
Implement proper fallbacks, handle feature detection, maintain core functionality, consider browser support, and implement proper enhancement strategies.
Implement proper build process, optimize asset delivery, handle environment variables, implement proper CI/CD, and consider deployment strategies.
Manage tokens securely, handle token refresh, implement interceptors for requests, manage auth state. Consider session management and security implications.
Use caching libraries (React Query, SWR), implement local storage caching, handle cache invalidation, manage cache lifecycle. Consider cache strategies and freshness.
Implement WebSocket connections, handle Socket.IO integration, manage real-time state updates, handle connection states. Consider reconnection strategies and data consistency.
Implement request debouncing/throttling, batch requests when possible, optimize payload size, use proper caching strategies. Consider performance and bandwidth usage.
Implement service workers, handle offline storage, manage sync queues, handle conflict resolution. Consider offline-first architecture and data synchronization.
Update UI immediately before API confirmation, handle rollback on failure, manage temporary state, implement proper error recovery. Consider user experience and data consistency.
Implement request queuing, handle rate limit errors, manage retry strategies, provide user feedback. Consider backend limitations and optimization strategies.
Implement proper authentication/authorization, handle CORS, prevent XSS attacks, manage sensitive data. Consider security best practices and vulnerabilities.
Handle sequential requests, manage request priority, implement queue processing logic. Consider error handling and queue management.
Track request times, monitor error rates, implement performance metrics, analyze bottlenecks. Consider monitoring tools and optimization strategies.
Use Apollo Client or other GraphQL clients, manage queries and mutations, handle caching, implement proper error handling. Consider GraphQL-specific optimizations.
Implement request combining, manage batch processing, handle response correlation, optimize network usage. Consider performance and complexity trade-offs.
Implement local storage caching, handle state rehydration, manage persistence lifecycle. Consider storage strategies and state management.
Be fluent in JSX, state management, and the component lifecycle.
Practice creating modular and reusable UI components.
Familiarize yourself with React hooks, Context API, and the latest React features.
Showcase personal or collaborative projects using ReactJS.
Join thousands of successful candidates preparing with Stark.ai. Start practicing ReactJS questions, mock interviews, and more to secure your dream role.
Start Preparing now