{jsonbody.com}

React.js Interview Coding Problems & Solutions

Master frontend React coding rounds with 200 practical coding problems, custom hooks, UI components, and expert solutions.

Q1. Build a custom useLocalStorage hook

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.log(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

Synchronizes React state with browser localStorage with lazy initialization and error handling.

Q2. Build a custom useDebounce hook

import { useState, useEffect } from 'react';

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

Delays updating value until a specified timeout duration passes without changes.

Q3. Build a custom useFetch data hook with cleanup

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    setLoading(true);

    fetch(url, { signal: controller.signal })
      .then(res => res.json())
      .then(data => { setData(data); setLoading(false); })
      .catch(err => {
        if (err.name !== 'AbortError') { setError(err); setLoading(false); }
      });

    return () => controller.abort();
  }, [url]);

  return { data, loading, error };
}

Handles asynchronous data fetching with automatic cancellation on unmount using AbortController.

Q4. Build a custom useMediaQuery hook

import { useState, useEffect } from 'react';

function useMediaQuery(query) {
  const [matches, setMatches] = useState(window.matchMedia(query).matches);

  useEffect(() => {
    const media = window.matchMedia(query);
    const listener = () => setMatches(media.matches);
    media.addEventListener('checked', listener);
    return () => media.removeEventListener('checked', listener);
  }, [query]);

  return matches;
}

Listens and responds dynamically to CSS media query breakpoints.

Q5. Build a custom usePrevious value hook

import { useRef, useEffect } from 'react';

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

Stores and returns the previous render scope value using useRef.

Q6. Implement a Counter component with increment, decrement, and reset

import { useState } from 'react';

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

Demonstrates basic functional state management and updater callbacks.

Q7. Build a simple Todo List component with add and delete

import { useState } from 'react';

export default function TodoList() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  const addTodo = () => {
    if (!input.trim()) return;
    setTodos([...todos, { id: Date.now(), text: input }]);
    setInput('');
  };

  return (
    <div>
      <input value={input} onChange={e => setInput(e.target.value)} />
      <button onClick={addTodo}>Add</button>
      <ul>
        {todos.map(t => (
          <li key={t.id}>{t.text} <button onClick={() => setTodos(todos.filter(x => x.id !== t.id))}>X</button></li>
        ))}
      </ul>
    </div>
  );
}

Manages list state arrays immutably with unique keys.

Q8. Build a Search Filter autocomplete component

import { useState } from 'react';

export default function Autocomplete({ items }) {
  const [query, setQuery] = useState('');
  const filtered = items.filter(i => i.toLowerCase().includes(query.toLowerCase()));
  return (
    <div>
      <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search..." />
      <ul>{filtered.map((item, idx) => <li key={idx}>{item}</li>)}</ul>
    </div>
  );
}

Filters arrays dynamically based on user search input.

Q9. Build a Modal component with Portal

import ReactDOM from 'react-dom';

export default function Modal({ isOpen, onClose, children }) {
  if (!isOpen) return null;
  return ReactDOM.createPortal(
    <div className="modal-overlay">
      <div className="modal-content">
        <button onClick={onClose}>Close</button>
        {children}
      </div>
    </div>,
    document.body
  );
}

Renders overlay modals outside root DOM hierarchy using ReactDOM.createPortal.

Q10. Build an Accordion component

import { useState } from 'react';

export default function Accordion({ title, content }) {
  const [isOpen, setIsOpen] = useState(false);
  return (
    <div className="accordion">
      <div onClick={() => setIsOpen(!isOpen)}>{title} {isOpen ? '-' : '+'}</div>
      {isOpen && <div className="content">{content}</div>}
    </div>
  );
}

Toggles visibility state for collapsible content panels.

Q11. Build an Infinite Scroll component

import { useState, useEffect } from 'react';

export default function InfiniteScroll() {
  const [items, setItems] = useState(Array.from({ length: 20 }));
  const [hasMore, setHasMore] = useState(true);

  useEffect(() => {
    const handleScroll = () => {
      if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 50) {
        setItems(prev => [...prev, ...Array.from({ length: 10 })]);
      }
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return <ul>{items.map((_, i) => <li key={i}>Item {i + 1}</li>)}</ul>;
}

Appends more items dynamically when user scrolls near page bottom.

Q12. Build a Star Rating component

import { useState } from 'react';

export default function StarRating({ totalStars = 5 }) {
  const [rating, setRating] = useState(0);
  const [hover, setHover] = useState(0);
  return (
    <div>
      {[...Array(totalStars)].map((_, i) => {
        const ratingValue = i + 1;
        return (
          <span key={i} style={{ color: ratingValue <= (hover || rating) ? 'gold' : 'gray', cursor: 'pointer' }}
                onClick={() => setRating(ratingValue)}
                onMouseEnter={() => setHover(ratingValue)}
                onMouseLeave={() => setHover(0)}>★</span>
        );
      })}
    </div>
  );
}

Manages active and hover rating states for interactive star UI.

Q13. Build a Pagination component

export default function Pagination({ totalPages, currentPage, onPageChange }) {
  return (
    <div className="pagination">
      {[...Array(totalPages)].map((_, i) => (
        <button key={i} disabled={currentPage === i + 1} onClick={() => onPageChange(i + 1)}>
          {i + 1}
        </button>
      ))}
    </div>
  );
}

Renders button lists to navigate between multi-page data views.

Q14. Build a Password Strength Meter component

import { useState } from 'react';

export default function PasswordStrength() {
  const [pass, setPass] = useState('');
  const getStrength = (p) => {
    let score = 0;
    if (p.length > 7) score++;
    if (/[A-Z]/.test(p)) score++;
    if (/[0-9]/.test(p)) score++;
    if (/[^A-Za-z0-9]/.test(p)) score++;
    return score;
  };
  return (
    <div>
      <input type="password" value={pass} onChange={e => setPass(e.target.value)} />
      <p>Strength Score: {getStrength(pass)} / 4</p>
    </div>
  );
}

Evaluates password strings against regular expression complexity rules.

Q15. Build a Dark Mode toggle using React Context

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

const ThemeContext = createContext();

export function ThemeProvider({ children }) {
  const [dark, setDark] = useState(false);
  return (
    <ThemeContext.Provider value={{ dark, setDark }}>
      <div className={dark ? 'dark-theme' : 'light-theme'}>{children}</div>
    </ThemeContext.Provider>
  );
}
export const useTheme = () => useContext(ThemeContext);

Shares global theme state across components without prop drilling.

Q16. Build a custom useTimeout hook

import { useEffect, useRef } from 'react';

function useTimeout(callback, delay) {
  const savedCallback = useRef();
  useEffect(() => { savedCallback.current = callback; }, [callback]);
  useEffect(() => {
    if (delay === null) return;
    const id = setTimeout(() => savedCallback.current(), delay);
    return () => clearTimeout(id);
  }, [delay]);
}

Manages safe asynchronous timeout callbacks inside functional components.

Q17. Build a custom useInterval hook

import { useEffect, useRef } from 'react';

function useInterval(callback, delay) {
  const savedCallback = useRef();
  useEffect(() => { savedCallback.current = callback; }, [callback]);
  useEffect(() => {
    if (delay === null) return;
    const id = setInterval(() => savedCallback.current(), delay);
    return () => clearInterval(id);
  }, [delay]);
}

Executes repeating interval loops safely using refs.

Q18. Build a custom useWindowSize hook

import { useState, useEffect } from 'react';

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;
}

Tracks and updates browser window dimensions reactively.

Q19. Build a custom useHover hook

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

function useHover() {
  const [isHovered, setIsHovered] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const node = ref.current;
    if (!node) return;
    const handleMouseEnter = () => setIsHovered(true);
    const handleMouseLeave = () => setIsHovered(false);
    node.addEventListener('mouseenter', handleMouseEnter);
    node.addEventListener('mouseleave', handleMouseLeave);
    return () => {
      node.removeEventListener('mouseenter', handleMouseEnter);
      node.removeEventListener('mouseleave', handleMouseLeave);
    };
  }, []);
  return [ref, isHovered];
}

Detects mouse hover states on arbitrary DOM elements.

Q20. Build a custom useToggle hook

import { useState, useCallback } from 'react';

function useToggle(initialState = false) {
  const [state, setState] = useState(initialState);
  const toggle = useCallback(() => setState(state => !state), []);
  return [state, toggle];
}

Provides boolean toggle state helpers with optimized callbacks.

Q21. Build a Tabs Component

import { useState } from 'react';

export default function Tabs({ tabs }) {
  const [activeTab, setActiveTab] = useState(0);
  return (
    <div>
      <div className="tab-headers">
        {tabs.map((tab, idx) => (
          <button key={idx} onClick={() => setActiveTab(idx)} style={{ fontWeight: activeTab === idx ? 'bold' : 'normal' }}>
            {tab.label}
          </button>
        ))}
      </div>
      <div className="tab-content">
        {tabs[activeTab].content}
      </div>
    </div>
  );
}

Switches visibility between different tab view panels.

Q22. Build a Tooltip Component

import { useState } from 'react';

export default function Tooltip({ text, children }) {
  const [show, setShow] = useState(false);
  return (
    <div style={{ position: 'relative', display: 'inline-block' }} onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}>
      {children}
      {show && <div style={{ position: 'absolute', bottom: '100%', left: '50%', transform: 'translateX(-50%)', background: '#333', color: '#fff', padding: '4px 8px', borderRadius: '4px', fontSize: '12px' }}>{text}</div>}
    </div>
  );
}

Displays floating hint text when hovering over child elements.

Q23. Build a Breadcrumb Navigation Component

export default function Breadcrumbs({ paths }) {
  return (
    <nav>
      {paths.map((p, idx) => (
        <span key={idx}>
          <a href={p.url}>{p.name}</a>
          {idx < paths.length - 1 && ' / '}
        </span>
      ))}
    </nav>
  );
}

Renders hierarchical location trail links.

Q24. Build a Carousel / Image Slider Component

import { useState } from 'react';

export default function Carousel({ images }) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const nextSlide = () => setCurrentIndex(prev => (prev === images.length - 1 ? 0 : prev + 1));
  const prevSlide = () => setCurrentIndex(prev => (prev === 0 ? images.length - 1 : prev - 1));
  return (
    <div>
      <button onClick={prevSlide}>Prev</button>
      <img src={images[currentIndex]} alt="slide" style={{ width: '300px' }} />
      <button onClick={nextSlide}>Next</button>
    </div>
  );
}

Cycles through image arrays iteratively with next and previous controls.

Q25. Build a Progress Bar Component

export default function ProgressBar({ progress }) {
  return (
    <div style={{ width: '100%', background: '#e0e0e0', borderRadius: '4px' }}>
      <div style={{ width: `${progress}%`, background: '#2563eb', height: '10px', borderRadius: '4px', transition: 'width 0.3s' }} />
    </div>
  );
}

Dynamically visualizes completion percentages.

Q26. Build a Pin / OTP Input Component

import { useState, useRef } from 'react';

export default function OtpInput({ length = 4, onComplete }) {
  const [otp, setOtp] = useState(Array(length).fill(''));
  const inputs = useRef([]);

  const handleChange = (val, index) => {
    if (isNaN(val)) return;
    const newOtp = [...otp];
    newOtp[index] = val;
    setOtp(newOtp);
    if (val && index < length - 1) inputs.current[index + 1].focus();
    if (newOtp.every(v => v !== '')) onComplete(newOtp.join(''));
  };

  return (
    <div style={{ display: 'flex', gap: '8px' }}>
      {otp.map((data, index) => (
        <input key={index} type="text" maxLength="1" value={data} ref={el => inputs.current[index] = el} onChange={e => handleChange(e.target.value, index)} style={{ width: '40px', textAlign: 'center' }} />
      ))}
    </div>
  );
}

Manages individual digit focus transitions for verification codes.

Q27. Build a Markdown Previewer Component

import { useState } from 'react';

export default function MarkdownPreviewer() {
  const [input, setInput] = useState('# Hello World');
  return (
    <div style={{ display: 'flex', gap: '20px' }}>
      <textarea value={input} onChange={e => setInput(e.target.value)} style={{ width: '50%', height: '200px' }} />
      <div style={{ width: '50%' }}>{input}</div>
    </div>
  );
}

Provides live text input previewing containers.

Q28. Build a Stopwatch / Timer Component

import { useState, useEffect } from 'react';

export default function Stopwatch() {
  const [seconds, setSeconds] = useState(0);
  const [isActive, setIsActive] = useState(false);

  useEffect(() => {
    let interval = null;
    if (isActive) {
      interval = setInterval(() => setSeconds(s => s + 1), 1000);
    } else if (!isActive && seconds !== 0) {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isActive, seconds]);

  return (
    <div>
      <h1>{seconds}s</h1>
      <button onClick={() => setIsActive(!isActive)}>{isActive ? 'Pause' : 'Start'}</button>
      <button onClick={() => { setIsActive(false); setSeconds(0); }}>Reset</button>
    </div>
  );
}

Implements secondary timer counters with play, pause, and reset triggers.

Q29. Build a File Dropzone Upload Component

import { useState } from 'react';

export default function Dropzone() {
  const [dragOver, setDragOver] = useState(false);
  const handleDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    const files = e.dataTransfer.files;
    console.log(files);
  };
  return (
    <div onDragOver={e => { e.preventDefault(); setDragOver(true); }} onDragLeave={() => setDragOver(false)} onDrop={handleDrop} style={{ border: '2px dashed #2563eb', padding: '40px', textAlign: 'center', background: dragOver ? '#eff6ff' : '#fff' }}>
      Drag & Drop files here
    </div>
  );
}

Captures file objects dragged and dropped into browser drop zones.

Q30. Build a Like Button Component with Animation State

import { useState } from 'react';

export default function LikeButton() {
  const [liked, setLiked] = useState(false);
  return (
    <button onClick={() => setLiked(!liked)} style={{ color: liked ? 'red' : 'gray', fontSize: '24px', background: 'none', border: 'none', cursor: 'pointer' }}>
      {liked ? '❤️' : '🤍'}
    </button>
  );
}

Toggles heart emoji states and styling dynamically.

Q31. Build a Tag Input / Chips Component

import { useState } from 'react';

export default function TagInput() {
  const [tags, setTags] = useState(['React', 'JavaScript']);
  const [input, setInput] = useState('');

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && input.trim()) {
      setTags([...tags, input.trim()]);
      setInput('');
    }
  };

  return (
    <div>
      <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginBottom: '8px' }}>
        {tags.map((tag, idx) => (
          <span key={idx} style={{ background: '#e2e8f0', padding: '4px 8px', borderRadius: '4px' }}>
            {tag} <button onClick={() => setTags(tags.filter((_, i) => i !== idx))}>x</button>
          </span>
        ))}
      </div>
      <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={handleKeyDown} placeholder="Add tag..." />
    </div>
  );
}

Manages arrays of tag chips created via Enter key strokes.

Q32. Build a Color Picker Component

import { useState } from 'react';

export default function ColorPicker() {
  const [color, setColor] = useState('#2563eb');
  return (
    <div>
      <input type="color" value={color} onChange={e => setColor(e.target.value)} />
      <div style={{ width: '100px', height: '100px', background: color, marginTop: '10px' }} />
    </div>
  );
}

Binds native color inputs to preview container backgrounds.

Q33. Build a Multi-step Wizard Form Component

import { useState } from 'react';

export default function WizardForm() {
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({ name: '', email: '' });

  return (
    <div>
      {step === 1 && <input placeholder="Name" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} />}
      {step === 2 && <input placeholder="Email" value={formData.email} onChange={e => setFormData({...formData, email: e.target.value})} />}
      <div>
        {step > 1 && <button onClick={() => setStep(s => s - 1)}>Back</button>}
        {step < 2 ? <button onClick={() => setStep(s => s + 1)}>Next</button> : <button onClick={() => alert('Submitted')}>Submit</button>}
      </div>
    </div>
  );
}

Splits complex form workflows into sequential wizard steps.

Q34. Build a Copy to Clipboard Component

import { useState } from 'react';

export default function CopyClipboard({ text }) {
  const [copied, setCopied] = useState(false);
  const handleCopy = () => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  return (
    <button onClick={handleCopy}>
      {copied ? 'Copied!' : 'Copy to Clipboard'}
    </button>
  );
}

Writes text strings to browser system clipboards with temporal feedback.

Q35. Build a Rating Emoji Feedback Component

import { useState } from 'react';

export default function EmojiFeedback() {
  const [selected, setSelected] = useState(null);
  const emojis = ['😠', '🙁', '😐', '😊', '😍'];
  return (
    <div style={{ display: 'flex', gap: '10px', fontSize: '24px' }}>
      {emojis.map((emoji, idx) => (
        <span key={idx} onClick={() => setSelected(idx)} style={{ cursor: 'pointer', opacity: selected === idx ? 1 : 0.4 }}>
          {emoji}
        </span>
      ))}
    </div>
  );
}

Allows users to express sentiment via selectable emoji scales.

Q36. Build a Read More / Read Less Text Component

import { useState } from 'react';

export default function ReadMore({ text, limit = 50 }) {
  const [isExpanded, setIsExpanded] = useState(false);
  if (text.length <= limit) return <p>{text}</p>;
  return (
    <p>
      {isExpanded ? text : `${text.substring(0, limit)}...`}
      <button onClick={() => setIsExpanded(!isExpanded)} style={{ background: 'none', border: 'none', color: 'blue', cursor: 'pointer' }}>
        {isExpanded ? 'Read Less' : 'Read More'}
      </button>
    </p>
  );
}

Truncates long text descriptions with expandable toggle links.

Q37. Build a Sortable Table Component

import { useState } from 'react';

export default function SortableTable({ data }) {
  const [sortField, setSortField] = useState('name');
  const [order, setOrder] = useState('asc');

  const sorted = [...data].sort((a, b) => {
    if (a[sortField] < b[sortField]) return order === 'asc' ? -1 : 1;
    if (a[sortField] > b[sortField]) return order === 'asc' ? 1 : -1;
    return 0;
  });

  return (
    <table>
      <thead>
        <tr>
          <th onClick={() => { setSortField('name'); setOrder(order === 'asc' ? 'desc' : 'asc'); }}>Name</th>
          <th onClick={() => { setSortField('age'); setOrder(order === 'asc' ? 'desc' : 'asc'); }}>Age</th>
        </tr>
      </thead>
      <tbody>
        {sorted.map((row, i) => <tr key={i}><td>{row.name}</td><td>{row.age}</td></tr>)}
      </tbody>
    </table>
  );
}

Sorts tabular records dynamically based on selected column headers.

Q38. Build a Custom Context Auth Wrapper Component

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

const AuthContext = createContext();

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const login = (userData) => setUser(userData);
  const logout = () => setUser(null);
  return <AuthContext.Provider value={{ user, login, logout }}>{children}</AuthContext.Provider>;
}
export const useAuth = () => useContext(AuthContext);

Supplies global authentication state and modifier methods across React apps.

Q39. Build a Debounced Search Input Component

import { useState, useEffect } from 'react';

export default function DebouncedSearch({ onSearch }) {
  const [text, setText] = useState('');
  useEffect(() => {
    const timer = setTimeout(() => {
      onSearch(text);
    }, 500);
    return () => clearTimeout(timer);
  }, [text, onSearch]);

  return <input value={text} onChange={e => setText(e.target.value)} placeholder="Search..." />;
}

Triggers search callbacks only after typing pauses.

Q40. Build an Image Gallery with Lightbox Preview

import { useState } from 'react';

export default function LightboxGallery({ images }) {
  const [activeImg, setActiveImg] = useState(null);
  return (
    <div>
      <div style={{ display: 'flex', gap: '10px' }}>
        {images.map((img, i) => <img key={i} src={img} onClick={() => setActiveImg(img)} style={{ width: '100px', cursor: 'pointer' }} />)}
      </div>
      {activeImg && (
        <div onClick={() => setActiveImg(null)} style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.8)', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <img src={activeImg} style={{ maxHeight: '80%' }} />
        </div>
      )}
    </div>
  );
}

Displays thumbnail galleries with fullscreen modal lightbox previews.

Q41. Build a Simple Calculator Component

import { useState } from 'react';

export default function Calculator() {
  const [input, setInput] = useState('');
  return (
    <div>
      <input value={input} readOnly />
      <div>
        {['1', '2', '3', '+', '4', '5', '6', '-', '7', '8', '9', '*', '0', 'C', '=', '/'].map((btn, i) => (
          <button key={i} onClick={() => {
            if (btn === 'C') setInput('');
            else if (btn === '=') try { setInput(eval(input)); } catch { setInput('Error'); }
            else setInput(input + btn);
          }}>{btn}</button>
        ))}
      </div>
    </div>
  );
}

Implements basic calculation logic with button grids.

Q42. Build a Weather Widget Card Component

import { useState } from 'react';

export default function WeatherWidget() {
  const [city] = useState('New York');
  const [temp] = useState(22);
  return (
    <div style={{ background: '#f0f9ff', padding: '20px', borderRadius: '8px' }}>
      <h3>Weather in {city}</h3>
      <p>{temp}°C Sunny</p>
    </div>
  );
}

Displays climate condition metrics in stylized card containers.

Q43. Build a Currency Converter Component

import { useState } from 'react';

export default function CurrencyConverter() {
  const [amount, setAmount] = useState(1);
  const rate = 83;
  return (
    <div>
      <input type="number" value={amount} onChange={e => setAmount(e.target.value)} /> USD
      <p>INR: {amount * rate}</p>
    </div>
  );
}

Performs mathematical currency conversion ratios.

Q44. Build a Random Quote Generator Component

import { useState } from 'react';

export default function QuoteGenerator() {
  const quotes = ['Code is like humor.', 'Simplicity is soul of efficiency.', 'Make it work, make it right, make it fast.'];
  const [quote, setQuote] = useState(quotes[0]);
  const getNewQuote = () => setQuote(quotes[Math.floor(Math.random() * quotes.length)]);
  return (
    <div>
      <p>"{quote}"</p>
      <button onClick={getNewQuote}>New Quote</button>
    </div>
  );
}

Pulls random items from arrays on button clicks.

Q45. Build a Step Progress Tracker Component

export default function StepTracker({ currentStep, steps }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
      {steps.map((step, idx) => (
        <div key={idx} style={{ fontWeight: currentStep === idx + 1 ? 'bold' : 'normal', color: currentStep >= idx + 1 ? 'blue' : 'gray' }}>
          {idx + 1}. {step}
        </div>
      ))}
    </div>
  );
}

Tracks progression states across multi-stage workflows.

Q46. Build a Simple Poll / Voting Widget Component

import { useState } from 'react';

export default function PollWidget() {
  const [votes, setVotes] = useState({ js: 10, python: 15 });
  return (
    <div>
      <button onClick={() => setVotes({ ...votes, js: votes.js + 1 })}>JavaScript: {votes.js}</button>
      <button onClick={() => setVotes({ ...votes, python: votes.python + 1 })}>Python: {votes.python}</button>
    </div>
  );
}

Tallies and records interactive voting selections.

Q47. Build a JSON Formatter Viewer Component

import { useState } from 'react';

export default function JsonViewer({ data }) {
  const [copied, setCopied] = useState(false);
  const jsonStr = JSON.stringify(data, null, 2);
  return (
    <div>
      <pre style={{ background: '#1e293b', color: '#fff', padding: '10px' }}>{jsonStr}</pre>
      <button onClick={() => { navigator.clipboard.writeText(jsonStr); setCopied(true); }}>{copied ? 'Copied' : 'Copy JSON'}</button>
    </div>
  );
}

Pretty prints JavaScript objects inside styled pre blocks.

Q48. Build a Font Size Adjuster Component

import { useState } from 'react';

export default function FontSizeAdjuster() {
  const [size, setSize] = useState(16);
  return (
    <div>
      <button onClick={() => setSize(s => s + 2)}>A+</button>
      <button onClick={() => setSize(s => Math.max(10, s - 2))}>A-</button>
      <p style={{ fontSize: `${size}px` }}>Dynamic font scaling preview text.</p>
    </div>
  );
}

Modifies inline text styling sizes dynamically.

Q49. Build a Character Counter Component

import { useState } from 'react';

export default function CharCounter({ limit = 100 }) {
  const [text, setText] = useState('');
  return (
    <div>
      <textarea value={text} onChange={e => setText(e.target.value)} maxLength={limit} />
      <p>{text.length} / {limit} characters remaining</p>
    </div>
  );
}

Monitors and restricts text input lengths.

Q50. Build a Simple Table Pagination Filter Component

import { useState } from 'react';

export default function TableFilter({ data }) {
  const [search, setSearch] = useState('');
  const filtered = data.filter(d => d.includes(search));
  return (
    <div>
      <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Filter table..." />
      <ul>{filtered.map((item, i) => <li key={i}>{item}</li>)}</ul>
    </div>
  );
}

Combines searching and filtering over dataset views.

Q51. ${id}. Comprehensive React UI Component Challenge ${id}

import { useState } from 'react';

export default function ChallengeComponent_${id}() {
  const [active, setActive] = useState(false);
  return (
    <div className="panel-${id}" style={{ border: '1px solid #ccc', padding: '15px' }}>
      <h4>Component Module ${id}</h4>
      <button onClick={() => setActive(!active)}>
        Status: {active ? 'Active' : 'Inactive'}
      </button>
    </div>
  );
}

Detailed React state encapsulation and UI rendering solution for architectural interview challenge number ${id}.