React case studies

30 React case studies available. Levels: fundamental (10), advanced (10), expert (10).
FundamentalReact

Applying dynamic styles and className in React

Context A status badge component must change its background color depending on the status value (success, warning, error). The Problem The team is using inline style objects with hard-coded color strings, making theming and maintenance difficult. Constraints Use a mapping object to associate each status to a CSS class name. Apply the class dynamically via className. Do not use inline styles. Expected Deliverable A React component that applies dynamic CSS class names based on a prop value using a mapping object, without relying on inline styles.

reactclassnamedynamic-styles+2
FundamentalReact

Composing components with children prop

Context A UI library needs a generic Card wrapper component that can wrap any content passed to it. The Problem The current Card component only accepts a title prop and hard-codes its inner content, making it impossible to reuse with different layouts. Constraints Use the children prop to render arbitrary nested content. Apply consistent wrapper styles (border, padding, shadow) in the Card. Demonstrate usage with at least two different inner contents. Expected Deliverable A React Card component using the children prop as a flexible content slot, demonstrating composition with different inner elements.

reactchildrencomposition+2
FundamentalReact

Conditional rendering based on state

Context A UI component must display different content depending on whether a user is logged in. The Problem The team is duplicating entire component trees and toggling CSS classes via JavaScript, rather than using React's conditional rendering patterns. Constraints Use a boolean state variable isLoggedIn. Render a welcome message when true, and a login prompt when false. Toggle the state with a button click. Expected Deliverable A React component demonstrating conditional rendering using a ternary operator or short-circuit evaluation based on a state variable.

reactconditional-renderingusestate+2
FundamentalReact

Creating your first React component

Context A development team is migrating a static HTML page to a React application. The Problem The current page contains a product card written in plain HTML with no reusability. Every time a new product needs to be displayed, the HTML is duplicated manually. Current Code <div class="card"> <h2>Product Name</h2> <p>$29.99</p> <button>Add to cart</button> </div> Constraints Create a functional component named ProductCard. Accept name and price as props. Render the card structure using JSX. Expected Deliverable A React functional component that renders a product card from props and can be reused across the application.

reactcomponentsprops+2
FundamentalReact

Fetching data with useEffect and displaying it

Context A team wants to display a list of users fetched from a public API on component mount. The Problem The data fetch is currently triggered on a button click inside an event handler, causing data to not appear on initial load. Constraints Use useEffect with an empty dependency array to fetch data on mount. Store the result in state with useState. Display a loading indicator while fetching. Expected Deliverable A React component that fetches data from a REST API on mount using useEffect, manages loading state, and renders the results.

reactuseeffectfetch+2
FundamentalReact

Handling form input with controlled components

Context A registration form needs to capture a user's name and email before submission. The Problem The form currently reads values directly from the DOM using document.getElementById, bypassing React's state management. Constraints Convert each input into a controlled component using useState. Bind the value and onChange props correctly. Log the form data on submit without reloading the page. Expected Deliverable A React form component using controlled inputs, with state-bound values and a submit handler that prevents default browser behavior.

reactformscontrolled-components+2
FundamentalReact

Lifting state up between sibling components

Context Two sibling components — a temperature input and a unit selector — need to stay in sync with each other. The Problem Each component manages its own local state independently, so changing the unit in one component does not update the displayed value in the other. Constraints Move the shared state to the closest common parent. Pass state and setter functions down as props. Do not use any global state library. Expected Deliverable A React implementation of the state lifting pattern, where a parent component coordinates state between two sibling components through props.

reactstate-liftingsibling-components+2
FundamentalReact

Managing local state with useState

Context A UI team is building a simple counter widget for a dashboard. The Problem The counter is currently implemented with vanilla JavaScript using direct DOM manipulation, which conflicts with React's rendering model. Current Code let count = 0; document.getElementById('btn').onclick = () => { count++; document.getElementById('display').innerText = count; }; Constraints Rewrite the counter as a React component using useState. Provide increment and decrement buttons. Display the current count value. Expected Deliverable A React component managing a numeric counter with useState, increment and decrement controls, and proper re-rendering on state change.

reactusestatestate+2
FundamentalReact

Passing functions as props to child components

Context A parent component manages a shopping cart, and a child component displays individual items with a remove button. The Problem The child component has no way to notify the parent when an item should be removed, so the remove button currently has no effect. Constraints Define the removeItem handler in the parent component. Pass it as a prop to the child component. Call the function from the child's button onClick. Expected Deliverable A React parent-child component pair demonstrating upward communication via callback props, correctly updating parent state from a child action.

reactpropscallbacks+2
FundamentalReact

Rendering a list of items with map()

Context An e-commerce application needs to display a list of products fetched from an API. The Problem The team is manually writing JSX for each product, making the code unmaintainable as the product catalog grows. Constraints Use the Array.map() method to render a list of product items. Assign a unique key prop to each element. Extract a reusable ListItem component. Expected Deliverable A React component that dynamically renders a list of items from an array using map(), with proper key props and a reusable child component.

reactlistmap+2
AdvancedReact

Building a custom hook for async data fetching

Context Multiple pages in an application each implement their own fetch logic with loading and error states, resulting in significant code duplication. The Problem Every component repeats the same useEffect + useState pattern for data fetching, making it hard to maintain and test centrally. Constraints Extract the logic into a custom hook named useFetch. Return { data, loading, error } from the hook. Handle component unmounting to prevent state updates on unmounted components. Expected Deliverable A reusable useFetch custom hook encapsulating async fetching with loading and error states, and cleanup logic to avoid memory leaks.

reactcustom-hookusefetch+2
AdvancedReact

Building an accessible modal with focus trapping

Context A modal dialog component is used for critical confirmations, but keyboard navigation breaks when the modal opens — focus escapes to the background. The Problem The modal does not trap focus within itself, making it unusable for keyboard and screen reader users, failing WCAG 2.1 AA criteria. Constraints Use useRef and useEffect to trap Tab focus within the modal. Return focus to the trigger element on close. Handle the Escape key to close the modal. Expected Deliverable An accessible React modal component with focus trapping, Escape key handling, and focus restoration on close, compliant with WCAG keyboard navigation requirements.

reactaccessibilitymodal+2
AdvancedReact

Code splitting and lazy loading with React.lazy and Suspense

Context A single-page application bundles all routes into one large JavaScript file, resulting in a 3MB initial load. The Problem Users wait several seconds before the application becomes interactive because every page's code is downloaded upfront. Constraints Use React.lazy() to dynamically import route components. Wrap lazy components with Suspense and provide a loading fallback. Apply the pattern to at least three routes. Expected Deliverable A React Router setup using React.lazy and Suspense for route-level code splitting, reducing the initial bundle size with a visible loading fallback.

reactlazysuspense+2
AdvancedReact

Compound component pattern for a flexible Tabs UI

Context A design system requires a Tabs component that is flexible enough for teams to customize the tab list and panel layout independently. The Problem The current Tabs component accepts all configuration as a single complex props object, making it rigid and hard to extend with custom tab header styles. Constraints Implement the compound component pattern with Tabs, Tabs.List, Tabs.Tab, and Tabs.Panel sub-components. Share active tab state through context internally. Expose no required configuration props beyond children. Expected Deliverable A React Tabs implementation using the compound component pattern with implicit state sharing via context, providing a flexible and composable API.

reactcompound-componentscontext+2
AdvancedReact

Global state management with useContext and useReducer

Context An application has authentication state (user, token, role) that needs to be accessible across deeply nested components without prop drilling. The Problem The auth state is currently passed through 5 levels of component props, making every intermediate component unnecessarily coupled to auth logic. Constraints Create an AuthContext with useContext. Manage state transitions with useReducer (LOGIN, LOGOUT actions). Provide the context at the root level and consume it in leaf components. Expected Deliverable A React context + reducer architecture for authentication state, demonstrating clean separation between context provider, reducer logic, and consumer components.

reactusecontextusereducer+2
AdvancedReact

Implementing a debounced search input with useRef

Context A search input triggers an API call on every keystroke, flooding the backend with hundreds of requests per second. The Problem The onChange handler calls the API directly without any delay mechanism, causing performance and cost issues. Constraints Implement debouncing using useRef to hold the timer reference. Wait 400ms after the last keystroke before firing the API call. Cancel the pending timer on each new keystroke. Expected Deliverable A React search input component implementing debounce with useRef and useEffect, reducing API calls to fire only after the user stops typing.

reactuserefdebounce+2
AdvancedReact

Implementing infinite scroll with IntersectionObserver

Context A social feed loads 20 posts at a time and must automatically load the next page when the user scrolls near the bottom. The Problem The team is using a scroll event listener on the window to detect the bottom of the page, which fires hundreds of times per scroll and causes jank. Constraints Replace the scroll listener with an IntersectionObserver targeting a sentinel element at the list bottom. Manage the observer lifecycle inside a useEffect. Append new results to the existing list without replacing it. Expected Deliverable A React infinite scroll implementation using IntersectionObserver, with correct observer cleanup and accumulative page data management.

reactinfinite-scrollintersectionobserver+2
AdvancedReact

Implementing optimistic UI updates

Context A todo application updates a task's completion status by calling a REST API, but the UI only updates after the server responds, causing a noticeable delay. The Problem The current approach waits for the API response before updating the UI, resulting in a laggy experience even on reliable connections. Constraints Apply the state change immediately in the UI before the API call resolves. Revert the state to its previous value if the API call fails. Show an error notification on failure. Expected Deliverable A React component implementing optimistic UI updates with automatic rollback on API failure, demonstrating the pattern with a toggle action.

reactoptimistic-uiusestate+2
AdvancedReact

Optimizing re-renders with React.memo and useCallback

Context A large dashboard renders a list of 200 rows. Each row contains an action button tied to a callback defined in the parent. The Problem Every state change in the parent causes all 200 row components to re-render, even when their data has not changed, causing visible UI lag. Constraints Wrap the row component with React.memo to skip unnecessary re-renders. Stabilize the callback reference using useCallback with correct dependencies. Verify the optimization using React DevTools Profiler. Expected Deliverable A React implementation demonstrating React.memo and useCallback working together to prevent unnecessary child re-renders, with an explanation of the dependency array choices.

reactmemousecallback+2
AdvancedReact

Performance optimization using useMemo for expensive computations

Context A data grid component computes a filtered and sorted list of 10,000 records on every render, causing noticeable frame drops when unrelated state changes. The Problem The filtering and sorting logic runs synchronously on every render regardless of whether the source data or filter criteria have changed. Constraints Wrap the filtering and sorting computation in useMemo. Define the dependency array to include only the data array and the active filter. Measure the improvement with React DevTools Profiler. Expected Deliverable A React data grid component using useMemo to memoize expensive computations, with a clear explanation of the dependency array and measured performance impact.

reactusememoperformance+2
ExpertReact

Architecting a micro-frontend shell with Module Federation

Context A large enterprise application must be split across four independent teams, each owning a separate React micro-frontend deployed independently. The Problem All four applications are bundled together, meaning a change in any team requires a full rebuild and redeployment of the entire application. Constraints Configure Webpack Module Federation for the shell and at least two remote micro-frontends. Share a single React instance across all remotes to avoid version conflicts. Implement error boundaries to isolate remote failures. Expected Deliverable A Module Federation shell application integrating two remote React micro-frontends, with shared React singleton and error boundary isolation per remote.

reactmicro-frontendmodule-federation+2
ExpertReact

Building a fully concurrent-safe data table with React 18 transitions

Context A financial dashboard renders a large sortable and filterable data table. Applying filters currently blocks the main thread, freezing the UI during heavy re-renders. The Problem Sorting or filtering 50,000 rows causes input fields to become unresponsive for several hundred milliseconds because the update is treated as urgent. Constraints Wrap non-urgent state updates (sort, filter) with startTransition from React 18. Use useTransition to display a pending indicator during the transition. Ensure input fields remain responsive at all times. Expected Deliverable A React 18 data table using useTransition to defer expensive rendering updates, demonstrating the concurrency model with a visible responsiveness improvement.

reactusetransitionconcurrent+2
ExpertReact

Building a real-time collaborative editor with operational transforms

Context A document editing platform must allow multiple users to edit the same document simultaneously without conflicts overwriting each other changes. The Problem The current last-write-wins strategy causes edits from simultaneous users to overwrite each other, losing data. Constraints Implement a basic operational transform algorithm to reconcile concurrent text insertions and deletions. Maintain a local pending operations queue. Synchronize via WebSocket and apply remote operations after transformation. Expected Deliverable A React collaborative text editor implementing basic operational transforms over WebSocket, correctly merging concurrent edits without data loss.

reactcollaborative-editingoperational-transforms+2
ExpertReact

Building a state machine-driven UI with XState

Context A multi-step payment flow has complex state transitions (idle to validating to processing to success or failure) with conditional logic and side effects. The Problem The current implementation uses multiple useState booleans that can reach impossible combinations, causing intermittent UI bugs. Constraints Model the payment flow as an XState state machine with explicit states and transitions. Integrate the machine with React using useMachine. Guarantee that impossible states cannot occur. Expected Deliverable A React payment flow component driven by an XState state machine, eliminating impossible state combinations and providing predictable UI transitions.

reactxstatestate-machine+2
ExpertReact

Designing a plugin system with dynamic component registration

Context A CMS platform needs to support third-party widget plugins that can be registered at runtime and rendered inside a page builder. The Problem The current implementation hard-codes all available widget types in a switch statement, requiring a full rebuild to add new widget types. Constraints Create a component registry (Map or object) allowing dynamic registration of components by string key. Render registered components lazily using React.lazy. Handle unknown keys gracefully with a fallback component. Expected Deliverable A React plugin architecture with a dynamic component registry, lazy loading, and graceful fallback for unregistered types.

reactplugin-systemregistry+2
ExpertReact

Designing a scalable design token system with CSS-in-JS and React context

Context A design system must support multiple themes (light, dark, high-contrast) that can be switched at runtime without page reload. The Problem Theme values are currently hard-coded in component files, making it impossible to switch themes globally or support user preferences. Constraints Define design tokens (colors, spacing, typography) as structured JavaScript objects. Distribute the active theme through React context. Support runtime theme switching and persist the preference to localStorage. Integrate with a CSS-in-JS library. Expected Deliverable A React theming architecture using context-distributed design tokens, runtime theme switching, persistence, and CSS-in-JS integration.

reactdesign-tokenstheming+2
ExpertReact

Implementing a drag-and-drop kanban board with react-dnd

Context A project management tool requires a Kanban board where cards can be dragged between columns and reordered within a column. The Problem The current implementation uses HTML5 drag events directly, producing inconsistent behavior across browsers and no visual drag preview. Constraints Use react-dnd with the HTML5 backend. Implement useDrag on cards and useDrop on columns and card slots. Update the underlying state immutably on each drop event. Show a drag preview during the drag gesture. Expected Deliverable A React Kanban board using react-dnd for cross-column drag-and-drop, with correct immutable state updates and a custom drag preview.

reactdrag-and-dropreact-dnd+2
ExpertReact

Implementing a render pipeline with Server Components and Client Components

Context A Next.js 14 application serves a product detail page that combines static server-rendered content with interactive client-side widgets. The Problem The entire page is currently a Client Component, causing unnecessary JavaScript to be sent to the browser for content that never changes after render. Constraints Design a clear Server Component / Client Component boundary. Fetch data in the Server Component without useEffect. Use the use client directive only where interactivity is required. Avoid passing non-serializable props across the boundary. Expected Deliverable A Next.js 14 page architecture demonstrating the correct Server/Client Component split, with server-side data fetching and minimal client-side JavaScript.

reactserver-componentsnextjs+2
ExpertReact

Implementing a virtualized list with react-window for 100k rows

Context An admin panel must display a searchable list of 100,000 log entries without pagination. The Problem Rendering all rows simultaneously causes 15+ second initial load times and makes scrolling completely unusable. Constraints Use FixedSizeList from react-window to virtualize the row rendering. Integrate search filtering without disabling virtualization. Handle dynamic row heights if entries vary in size. Expected Deliverable A React virtualized list implementation using react-window that renders 100k rows performantly, with integrated search filtering and stable scroll behavior.

reactvirtualizationreact-window+2
ExpertReact

Implementing end-to-end testing for a React app with Playwright

Context A critical checkout flow has no automated tests. Regressions are only discovered in production, causing revenue loss. The Problem The engineering team lacks an automated testing strategy covering user-visible behavior across the full checkout journey. Constraints Write Playwright tests covering: product selection, cart update, form validation, and successful order submission. Mock API responses for deterministic test runs. Assert on accessible roles and text content rather than CSS selectors. Expected Deliverable A Playwright test suite covering the full React checkout flow, using API mocking, role-based selectors, and assertions on visible UI state.

reactplaywrighte2e-testing+2

Original questions designed by CodeDuel. CodeDuel is not affiliated with any publisher or certification body mentioned; certification names and trademarks belong to their respective owners and are used only to indicate the area covered. Report content

    React case studies: 30 scenarios | CodeDuel