Table of Contents
Beginner-Level React Interview Questions
Intermediate-Level React Interview Questions
Expert-Level React Interview Questions
Conclusion
Beginner-Level React Interview Questions
These questions focus on foundational concepts, basic coding, and understanding React’s core principles, perfect for freshers or those new to React.
What is React, and why is it popular for building user interfaces?
Type: Basic Understanding
Expected Answer: React is an open-source JavaScript library for building user interfaces, particularly single-page applications. Its popularity stems from its component-based architecture, virtual DOM, and declarative syntax, enabling efficient and scalable UI development.
Example:
function App() { return <h1>Welcome to React!</h1>; }
What is JSX, and how does it differ from regular JavaScript?
Type: Basic Understanding
Expected Answer: JSX is a syntax extension that allows HTML-like code within JavaScript. It’s transpiled into React.createElement calls using tools like Babel, unlike regular JavaScript.
Example:
const element = <h1>Hello, World!</h1>; // Transpiled to: React.createElement('h1', null, 'Hello, World!');
What is the virtual DOM, and how does it improve performance?
Type: Conceptual
Expected Answer: The virtual DOM is an in-memory representation of the real DOM. React uses it for diffing, updating only changed elements, reducing costly DOM manipulations.
Scenario: How does the virtual DOM optimize updates in a list of 100 items when only one changes?
What’s the difference between props and state in React?
Type: Conceptual
Expected Answer: Props are immutable data passed from parent to child components, while state is mutable, managed within a component for dynamic updates.
Example:
function Greeting({ name }) { const [count, setCount] = useState(0); return ( <div> <h1>Hello, {name}!</h1> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
What are functional components, and why are they preferred?
Type: Conceptual
Expected Answer: Functional components are JavaScript functions returning JSX. They’re preferred for their simplicity, support for hooks, and better performance over class components.
Coding Challenge: Create a counter component.
function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
Why is the key prop important in lists?
Type: Conceptual
Expected Answer: The key prop uniquely identifies list items, helping React efficiently update and re-render lists by tracking changes.
Example:
const items = ['Apple', 'Banana', 'Orange']; const list = items.map((item, index) => <li key={index}>{item}</li>);
How do you create a new React project?
Type: Practical
Expected Answer: Use npx create-react-app my-app to set up a React project with pre-configured tools like Webpack and Babel.
What are controlled components?
Type: Practical
Expected Answer: Controlled components are form elements whose values are managed by React state, ensuring a single source of truth.
Example:
function InputForm() { const [value, setValue] = useState(''); return ( <input type="text" value={value} onChange={(e) => setValue(e.target.value)} /> ); }
What is the useState hook, and how is it used?
Type: Practical
Expected Answer: useState adds state to functional components, returning a state variable and an updater function.
Coding Challenge: Build a form displaying input in real-time.
function InputDisplay() { const [input, setInput] = useState(''); return ( <div> <input type="text" value={input} onChange={(e) => setInput(e.target.value)} /> <p>Input: {input}</p> </div> ); }
How does React handle events differently from vanilla JavaScript?
Type: Conceptual
Expected Answer: React uses synthetic events, a cross-browser wrapper around native events, providing a consistent API and automatic cleanup.
Example:
function Button() { const handleClick = () => alert('Clicked!'); return <button onClick={handleClick}>Click Me</button>; }
What is the role of ReactDOM.render?
Type: Conceptual
Expected Answer: ReactDOM.render renders a React element into a DOM node, typically the root element of an application.
Example:
ReactDOM.render(<App />, document.getElementById('root'));
What is one-way data binding in React?
Type: Conceptual
Expected Answer: One-way data binding means data flows from parent to child components via props, ensuring predictable state updates.
How do you pass data between components?
Type: Practical
Expected Answer: Pass data via props from parent to child, or use callbacks to send data back to the parent.
Example:
function Parent() { const [data, setData] = useState(''); return <Child setData={setData} data={data} />; } function Child({ setData, data }) { return <input onChange={(e) => setData(e.target.value)} value={data} />; }
What is the purpose of Babel in React?
Type: Conceptual
Expected Answer: Babel transpiles JSX and modern JavaScript (e.g., ES6+) into browser-compatible JavaScript.
How do you conditionally render components?
Type: Practical
Expected Answer: Use if-else, ternary operators, or logical operators in JSX for conditional rendering.
Example:
function ConditionalRender({ isActive }) { return isActive && <h1>Active Component</h1>; }
What are React fragments?
Type: Conceptual
Expected Answer: Fragments group multiple elements without adding extra DOM nodes, improving performance.
Example:
function List() { return ( <React.Fragment> <li>Item 1</li> <li>Item 2</li> </React.Fragment> ); }
Why is immutability important in React?
Type: Conceptual
Expected Answer: Immutability ensures predictable state updates and efficient rendering by enabling React to detect changes via reference comparison.
How do you style components in React?
Type: Practical
Expected Answer: Use inline styles, CSS modules, or libraries like styled-components.
Example:
const style = { color: 'blue' }; function StyledComponent() { return <h1 style={style}>Styled Text</h1>; }
What is the difference between controlled and uncontrolled components?
Type: Conceptual
Expected Answer: Controlled components use state to manage form values, while uncontrolled components rely on the DOM via refs.
How do you handle form submissions in React?
Type: Practical
Expected Answer: Use a controlled form with an onSubmit handler to process form data.
Example:
function Form() { const [value, setValue] = useState(''); const handleSubmit = (e) => { e.preventDefault(); console.log(value); }; return ( <form onSubmit={handleSubmit}> <input value={value} onChange={(e) => setValue(e.target.value)} /> <button type="submit">Submit</button> </form> ); }
What is the purpose of defaultProps?
Type: Conceptual
Expected Answer: defaultProps provides default values for props if they’re not passed.
Example:
function Greeting({ name }) { return <h1>Hello, {name}!</h1>; } Greeting.defaultProps = { name: 'Guest' };
How do you use the map function to render lists?
Type: Practical
Expected Answer: Use map to iterate over an array and return JSX elements with unique key props.
Example:
function List({ items }) { return ( <ul> {items.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> ); }
What are the benefits of React over vanilla JavaScript?
Type: Conceptual
Expected Answer: React offers a component-based structure, virtual DOM, and declarative syntax, simplifying complex UI development.
How do you debug a React application?
Type: Practical
Expected Answer: Use browser dev tools, React Developer Tools, and console logs to inspect components and state.
What is the significance of the React import?
Type: Conceptual
Expected Answer: The React import is required for JSX and React APIs, as JSX is transpiled into React.createElement calls.
How do you use inline styles in React?
Type: Practical
Expected Answer: Pass a style object to the style prop.
Example:
function StyledDiv() { return <div style={{ backgroundColor: 'blue', color: 'white' }}>Styled</div>; }
What is a React element vs. a React component?
Type: Conceptual
Expected Answer: A React element is an immutable description of a UI piece, while a component is a reusable function or class that produces elements.
How do you handle multiple inputs in a form?
Type: Practical
Expected Answer: Use a single state object with dynamic keys based on input name attributes.
Example:
function Form() { const [formData, setFormData] = useState({ name: '', email: '' }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; return ( <div> <input name="name" value={formData.name} onChange={handleChange} /> <input name="email" value={formData.email} onChange={handleChange} /> </div> ); }
What is the children prop in React?
Type: Conceptual
Expected Answer: The children prop represents content passed between a component’s opening and closing tags.
Example:
function Wrapper({ children }) { return <div>{children}</div>; }
How do you prevent unnecessary re-renders in React?
Type: Performance
Expected Answer: Use React.memo, useCallback, useMemo, or split components to minimize re-renders.
What is the purpose of useReducer hook?
Type: Practical
Expected Answer: useReducer manages complex state logic, similar to Redux, by dispatching actions to a reducer function.
Example:
function Counter() { const [state, dispatch] = useReducer((state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; default: return state; } }, { count: 0 }); return <button onClick={() => dispatch({ type: 'increment' })}> {state.count} </button>; }
How do you handle errors in React components?
Type: Practical
Expected Answer: Use error boundaries with componentDidCatch or try-catch in hooks.
Example:
class ErrorBoundary extends React.Component { state = { hasError: false }; componentDidCatch() { this.setState({ hasError: true }); } render() { return this.state.hasError ? <h1>Error!</h1> : this.props.children; } }
What is the significance of React.StrictMode?
Type: Conceptual
Expected Answer: React.StrictMode enables additional checks and warnings for potential issues during development.
How do you use CSS modules in React?
Type: Practical
Expected Answer: CSS modules scope styles locally by generating unique class names.
Example:
import styles from './styles.module.css'; function Component() { return <div className={styles.container}>Styled</div>; }
What is the difference between useState and useReducer?
Type: Conceptual
Expected Answer: useState is for simple state, while useReducer is for complex state logic with multiple actions.
How do you pass methods as props?
Type: Practical
Expected Answer: Define a method in the parent and pass it to the child via props.
Example:
function Parent() { const handleClick = () => console.log('Clicked'); return <Child onClick={handleClick} />; }
What is the purpose of the useRef hook?
Type: Practical
Expected Answer: useRef creates a mutable reference that persists across renders, often used for DOM access.
Example:
function InputFocus() { const inputRef = useRef(null); return ( <div> <input ref={inputRef} /> <button onClick={() => inputRef.current.focus()}>Focus</button> </div> ); }
How do you handle asynchronous operations in React?
Type: Practical
Expected Answer: Use useEffect with async/await or promises for async operations like API calls.
Example:
function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { async function fetchData() { const res = await fetch('https://api.example.com/data'); setData(await res.json()); } fetchData(); }, []); return <div>{data ? data.name : 'Loading...'}</div>; }
What is the role of dangerouslySetInnerHTML?
Type: Conceptual
Expected Answer: It sets raw HTML content in a component, but should be used cautiously due to XSS risks.
How do you use environment variables in a React app?
Type: Practical
Expected Answer: Use .env files and access variables via process.env.REACT_APP_VARIABLE.
What is the difference between componentDidMount and useEffect?
Type: Conceptual
Expected Answer: componentDidMount is a class component lifecycle method, while useEffect with an empty dependency array mimics it in functional components.
How do you manage state in a deeply nested component tree?
Type: Scenario-Based
Expected Answer: Use Context API or Redux to manage state across nested components.
What is the purpose of the shouldComponentUpdate method?
Type: Conceptual
Expected Answer: It controls whether a component should re-render, optimizing performance in class components.
How do you implement a toggle switch in React?
Type: Coding Challenge
Expected Answer:
function Toggle() { const [isOn, setIsOn] = useState(false); return ( <button onClick={() => setIsOn(!isOn)}> {isOn ? 'On' : 'Off'} </button> ); }
What is prop drilling, and how can it be avoided?
Type: Conceptual
Expected Answer: Prop drilling is passing props through multiple component layers. Avoid it using Context API or Redux.
How do you handle click events outside a component?
Type: Practical
Expected Answer: Use useEffect and useRef to detect clicks outside a component.
Example:
function OutsideClick() { const ref = useRef(); useEffect(() => { const handleClick = (e) => { if (!ref.current.contains(e.target)) { console.log('Clicked outside'); } }; document.addEventListener('click', handleClick); return () => document.removeEventListener('click', handleClick); }, []); return <div ref={ref}>Click outside this div</div>; }
What is the difference between useEffect and useLayoutEffect?
Type: Conceptual
Expected Answer: useEffect runs after rendering, while useLayoutEffect runs synchronously before painting, useful for DOM measurements.
How do you create a reusable button component?
Type: Coding Challenge
Expected Answer:
function Button({ type = 'button', children, onClick }) { return <button type={type} onClick={onClick}>{children}</button>; }
What is the purpose of React.memo?
Type: Performance
Expected Answer: React.memo prevents unnecessary re-renders of functional components by memoizing based on props.
How do you handle dynamic imports in React?
Type: Practical
Expected Answer: Use React.lazy and Suspense for dynamic imports to reduce bundle size.
Example:
const LazyComponent = React.lazy(() => import('./LazyComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); }
Intermediate-Level React Interview Questions
These questions target developers with 2–5 years of experience, focusing on real-world scenarios, hooks, routing, and optimization.
What is conditional rendering, and how is it implemented?
Type: Practical
Expected Answer: Conditional rendering displays UI based on conditions using if-else, ternary operators, or logical operators.
Example:
function UserStatus({ isLoggedIn }) { return isLoggedIn ? <h1>Welcome!</h1> : <h1>Please Log In</h1>; }
Scenario: Implement a loading spinner during data fetching.
What is the useEffect hook, and when does it run?
Type: Practical
Expected Answer: useEffect handles side effects and runs after renders or when dependencies change.
Example:
function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then((res) => res.json()) .then(setData); }, []); return <div>{data ? data.name : 'Loading...'}</div>; }
How do you optimize performance in a React application?
Type: Performance
Expected Answer: Use React.memo, useCallback, useMemo, code-splitting, and lazy loading.
Coding Challenge: Optimize a list component.
import React, { memo } from 'react'; const ItemList = memo(({ items }) => ( <ul> {items.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> ));
What are higher-order components (HOCs)?
Type: Conceptual
Expected Answer: HOCs are functions that enhance components with additional functionality, like authentication.
Example:
function withAuth(Component) { return (props) => { const isAuthenticated = checkAuth(); return isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />; }; }
How do you implement React Router?
Type: Practical
Expected Answer: Use BrowserRouter, Route, and Link for declarative routing.
Example:
import { BrowserRouter, Route, Link } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Link to="/">Home</Link> <Route path="/" exact component={Home} /> </BrowserRouter> ); }
What is Redux, and when should you use it?
Type: Conceptual
Expected Answer: Redux is a state management library for predictable state updates, ideal for complex, shared state.
Scenario: Manage a shopping cart in an e-commerce app.
What’s the difference between useCallback and useMemo?
Type: Practical
Expected Answer: useCallback memoizes functions, while useMemo memoizes values.
Example:
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]); const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
How do you handle forms with multiple inputs?
Type: Practical
Expected Answer: Use a state object with dynamic keys.
Example:
function Form() { const [formData, setFormData] = useState({ name: '', email: '' }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; return ( <form> <input name="name" value={formData.name} onChange={handleChange} /> <input name="email" value={formData.email} onChange={handleChange} /> </form> ); }
What is the purpose of React.Fragment?
Type: Conceptual
Expected Answer: Fragments group elements without adding DOM nodes.
Example:
function List() { return ( <React.Fragment> <li>Item 1</li> <li>Item 2</li> </React.Fragment> ); }
How do you implement lazy loading in React?
Type: Performance
Expected Answer: Use React.lazy and Suspense for dynamic imports.
Example:
const LazyComponent = React.lazy(() => import('./LazyComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); }
What are custom hooks, and how do you create one?
Type: Practical
Expected Answer: Custom hooks are reusable functions that encapsulate hook logic.
Example:
function useWindowSize() { const [size, setSize] = useState({ width: 0, height: 0 }); useEffect(() => { const updateSize = () => setSize({ width: window.innerWidth, height: window.innerHeight }); window.addEventListener('resize', updateSize); updateSize(); return () => window.removeEventListener('resize', updateSize); }, []); return size; }
How do you handle errors in React applications?
Type: Practical
Expected Answer: Use error boundaries for component-level errors and try-catch for async operations.
Example:
class ErrorBoundary extends React.Component { state = { hasError: false }; componentDidCatch() { this.setState({ hasError: true }); } render() { return this.state.hasError ? <h1>Error!</h1> : this.props.children; } }
What is the Context API, and when should you use it?
Type: Conceptual
Expected Answer: Context API provides a way to share data across components without prop drilling, ideal for global state like themes or user data.
Example:
const ThemeContext = React.createContext('light'); function App() { return ( <ThemeContext.Provider value="dark"> <ThemedComponent /> </ThemeContext.Provider> ); }
How do you test React components?
Type: Practical
Expected Answer: Use libraries like Jest and React Testing Library to test rendering, events, and state changes.
Example:
import { render, screen } from '@testing-library/react'; test('renders button', () => { render(<Button>Click</Button>); expect(screen.getByText('Click')).toBeInTheDocument(); });
What is the difference between useEffect and componentDidMount?
Type: Conceptual
Expected Answer: useEffect with an empty dependency array mimics componentDidMount, but runs after render, while componentDidMount is specific to class components.
How do you implement a search filter in React?
Type: Coding Challenge
Expected Answer:
function SearchFilter({ items }) { const [query, setQuery] = useState(''); const filtered = items.filter((item) => item.name.toLowerCase().includes(query.toLowerCase()) ); return ( <div> <input value={query} onChange={(e) => setQuery(e.target.value)} /> <ul> {filtered.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); }
What is the role of useMemo in performance optimization?
Type: Performance
Expected Answer: useMemo memoizes expensive computations to prevent recalculation on every render.
Example:
function ExpensiveComponent({ data }) { const memoizedValue = useMemo(() => computeExpensive(data), [data]); return <div>{memoizedValue}</div>; }
How do you handle routing with URL parameters?
Type: Practical
Expected Answer: Use useParams from React Router to access URL parameters.
Example:
import { useParams } from 'react-router-dom'; function UserProfile() { const { id } = useParams(); return <h1>User ID: {id}</h1>; }
What are the benefits of using hooks over class components?
Type: Conceptual
Expected Answer: Hooks simplify code, enable state in functional components, and reduce boilerplate compared to class lifecycle methods.
How do you implement a modal in React?
Type: Coding Challenge
Expected Answer:
function Modal({ isOpen, onClose, children }) { if (!isOpen) return null; return ( <div className="modal"> <div className="modal-content"> <button onClick={onClose}>Close</button> {children} </div> </div> ); }
What is the purpose of useCallback?
Type: Practical
Expected Answer: useCallback memoizes functions to prevent re-creation, optimizing performance in child components.
Example:
const memoizedCallback = useCallback(() => console.log('Clicked'), []);
How do you manage global state without Redux?
Type: Practical
Expected Answer: Use Context API with useReducer for global state management.
Example:
const StateContext = React.createContext(); function App() { const [state, dispatch] = useReducer(reducer, initialState); return ( <StateContext.Provider value={{ state, dispatch }}> <Child /> </StateContext.Provider> ); }
What is the difference between shallow and deep rendering in testing?
Type: Conceptual
Expected Answer: Shallow rendering tests a component in isolation, while deep rendering includes child components.
How do you handle file uploads in React?
Type: Practical
Expected Answer: Use an input with type="file" and handle the onChange event.
Example:
function FileUpload() { const handleFile = (e) => { const file = e.target.files[0]; console.log(file); }; return <input type="file" onChange={handleFile} />; }
What is the purpose of React.PureComponent?
Type: Conceptual
Expected Answer: PureComponent performs shallow prop and state comparisons to prevent unnecessary re-renders in class components.
How do you implement pagination in React?
Type: Coding Challenge
Expected Answer:
function PaginatedList({ items }) { const [page, setPage] = useState(1); const itemsPerPage = 10; const paginated = items.slice((page - 1) * itemsPerPage, page * itemsPerPage); return ( <div> <ul> {paginated.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> <button onClick={() => setPage(page + 1)}>Next</button> </div> ); }
What are the challenges of using inline functions in JSX?
Type: Performance
Expected Answer: Inline functions create new references on every render, potentially causing unnecessary re-renders in child components.
How do you implement a dropdown menu in React?
Type: Coding Challenge
Expected Answer:
function Dropdown({ options }) { const [selected, setSelected] = useState(''); return ( <select value={selected} onChange={(e) => setSelected(e.target.value)}> {options.map((option) => ( <option key={option} value={option}>{option}</option> ))} </select> ); }
What is the role of useContext hook?
Type: Practical
Expected Answer: useContext accesses context values in functional components.
Example:
const ThemeContext = React.createContext('light'); function ThemedComponent() { const theme = useContext(ThemeContext); return <div>Theme: {theme}</div>; }
How do you handle API errors in React?
Type: Practical
Expected Answer: Use try-catch in async functions and display error messages.
Example:
function DataFetcher() { const [error, setError] = useState(null); useEffect(() => { async function fetchData() { try { const res = await fetch('https://api.example.com/data'); setData(await res.json()); } catch (err) { setError('Failed to fetch'); } } fetchData(); }, []); return <div>{error || 'Data loaded'}</div>; }
What is the difference between useState and useRef?
Type: Conceptual
Expected Answer: useState triggers re-renders on updates, while useRef persists values without re-rendering.
How do you implement a timer in React?
Type: Coding Challenge
Expected Answer:
function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => setSeconds((s) => s + 1), 1000); return () => clearInterval(interval); }, []); return <div>Seconds: {seconds}</div>; }
What is the role of Suspense in React?
Type: Conceptual
Expected Answer: Suspense handles asynchronous rendering, like lazy-loaded components or data fetching.
How do you implement a toggleable sidebar?
Type: Coding Challenge
Expected Answer:
function Sidebar() { const [isOpen, setIsOpen] = useState(false); return ( <div> <button onClick={() => setIsOpen(!isOpen)}>Toggle</button> {isOpen && <div className="sidebar">Sidebar Content</div>} </div> ); }
What is the difference between ReactDOM.render and ReactDOM.hydrate?
Type: Conceptual
Expected Answer: ReactDOM.render renders React elements to the DOM, while hydrate is used for server-side rendered apps to attach event listeners.
How do you handle multiple API calls in React?
Type: Practical
Expected Answer: Use Promise.all to handle multiple API calls concurrently.
Example:
function MultiFetcher() { const [data, setData] = useState([]); useEffect(() => { Promise.all([ fetch('https://api1.example.com'), fetch('https://api2.example.com'), ]) .then((responses) => Promise.all(responses.map((res) => res.json()))) .then(setData); }, []); return <div>{data.length} items loaded</div>; }
What is the purpose of useImperativeHandle?
Type: Practical
Expected Answer: useImperativeHandle customizes the instance value exposed when using ref in a functional component.
How do you implement a loading spinner for API calls?
Type: Coding Challenge
Expected Answer:
function DataLoader() { const [loading, setLoading] = useState(true); useEffect(() => { fetch('https://api.example.com/data') .then(() => setLoading(false)); }, []); return loading ? <div>Loading...</div> : <div>Data Loaded</div>; }
What is the role of useDebugValue?
Type: Conceptual
Expected Answer: useDebugValue provides custom labels for custom hooks in React DevTools.
How do you implement a form validation in React?
Type: Coding Challenge
Expected Answer:
function FormValidation() { const [formData, setFormData] = useState({ email: '' }); const [error, setError] = useState(''); const handleSubmit = (e) => { e.preventDefault(); if (!formData.email.includes('@')) setError('Invalid email'); else setError(''); }; return ( <form onSubmit={handleSubmit}> <input value={formData.email} onChange={(e) => setFormData({ email: e.target.value })} /> {error && <p>{error}</p>} <button type="submit">Submit</button> </form> ); }
What is the difference between ReactDOM.createPortal and regular rendering?
Type: Conceptual
Expected Answer: createPortal renders children into a different DOM node, useful for modals or popups.
How do you implement a reusable form component?
Type: Coding Challenge
Expected Answer:
function Form({ onSubmit, children }) { return <form onSubmit={onSubmit}>{children}</form>; }
What is the purpose of useTransition in React 18?
Type: Conceptual
Expected Answer: useTransition manages concurrent updates, allowing non-urgent updates to be interrupted by urgent ones.
How do you handle browser back/forward navigation in React Router?
Type: Practical
Expected Answer: Use useHistory or useNavigate to listen for navigation events.
What are the benefits of using TypeScript with React?
Type: Conceptual
Expected Answer: TypeScript provides type safety, better tooling, and improved maintainability.
How do you implement a carousel in React?
Type: Coding Challenge
Expected Answer:
function Carousel({ images }) { const [index, setIndex] = useState(0); return ( <div> <img src={images[index]} alt="carousel" /> <button onClick={() => setIndex((index + 1) % images.length)}>Next</button> </div> ); }
What is the role of useId in React 18?
Type: Conceptual
Expected Answer: useId generates unique IDs for accessibility in server-side rendering.
How do you handle real-time updates in React?
Type: Practical
Expected Answer: Use WebSockets or polling with useEffect.
Example:
function RealTimeData() { const [data, setData] = useState(null); useEffect(() => { const ws = new WebSocket('ws://example.com'); ws.onmessage = (e) => setData(e.data); return () => ws.close(); }, []); return <div>{data}</div>; }
What is the difference between client-side and server-side routing?
Type: Conceptual
Expected Answer: Client-side routing handles navigation in the browser, while server-side routing requires server requests.
How do you implement a sortable table in React?- Type: Coding Challenge - Expected Answer:
function SortableTable({ data }) { const [sortKey, setSortKey] = useState('name'); const sorted = [...data].sort((a, b) => a[sortKey].localeCompare(b[sortKey])); return ( <table> <thead> <tr> <th onClick={() => setSortKey('name')}>Name</th> </tr> </thead> <tbody> {sorted.map((item) => ( <tr key={item.id}><td>{item.name}</td></tr> ))} </tbody> </table> ); }
Expert-Level React Interview Questions
These questions challenge senior developers with complex scenarios, advanced patterns, and performance-critical tasks.
How do you implement a custom hook to cache API responses?- Type: Coding Challenge - Expected Answer:
function useCachedFetch(url) { const [data, setData] = useState(null); useEffect(() => { const cache = localStorage.getItem(url); if (cache) { setData(JSON.parse(cache)); return; } fetch(url) .then((res) => res.json()) .then((result) => { localStorage.setItem(url, JSON.stringify(result)); setData(result); }); }, [url]); return data; }
- **Scenario**: Extend this hook to include cache expiration.
How do you handle server-side rendering (SSR) in React?- Type: Practical - Expected Answer: Use Next.js or ReactDOMServer for SSR to improve SEO and initial load performance. - Example:
import { renderToString } from 'react-dom/server'; const html = renderToString(<App />);
How would you implement an undo feature in a React app?- Type: Coding Challenge - Expected Answer:
function TextEditor() { const [text, setText] = useState(''); const [history, setHistory] = useState([]); const handleChange = (e) => { setHistory([...history, text]); setText(e.target.value); }; const undo = () => { if (history.length > 0) { setText(history[history.length - 1]); setHistory(history.slice(0, -1)); } }; return ( <div> <textarea value={text} onChange={handleChange} /> <button onClick={undo}>Undo</button> </div> ); }
How do you optimize a React app for large datasets?- Type: Performance - Expected Answer: Use virtualization (e.g., react-window), pagination, and useMemo. - Scenario: Display a table with 10,000 rows efficiently.
What are the challenges of using Redux in large applications?- Type: Conceptual - Expected Answer: Challenges include boilerplate code, performance overhead, and debugging complexity. - Scenario: When would you choose Context API over Redux?
How do you implement a drag-and-drop feature in React?- Type: Coding Challenge - Expected Answer: Use libraries like react-dnd or native HTML5 drag-and-drop API. - Example:
function DraggableItem() { const handleDragStart = (e) => e.dataTransfer.setData('text', 'item'); return <div draggable onDragStart={handleDragStart}>Drag Me</div>; }
How do you handle concurrent rendering in React 18?- Type: Conceptual - Expected Answer: Use features like useTransition and startTransition to prioritize urgent updates.
What is the role of a custom reconciler in React?- Type: Conceptual - Expected Answer: A custom reconciler allows React to work with non-DOM renderers, like React Native or custom renderers.
How do you implement infinite scrolling in React?- Type: Coding Challenge - Expected Answer:
function InfiniteScroll() { const [items, setItems] = useState([]); useEffect(() => { const handleScroll = () => { if (window.innerHeight + window.scrollY >= document.body.offsetHeight) { setItems((prev) => [...prev, ...newItems()]); } }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); return <div>{items.map((item) => <div key={item.id}>{item.name}</div>)}</div>; }
How do you handle state persistence across page reloads?- Type: Practical - Expected Answer: Use localStorage or sessionStorage with useState or useEffect. - Example:
function PersistentState() { const [value, setValue] = useState(localStorage.getItem('value') || ''); useEffect(() => { localStorage.setItem('value', value); }, [value]); return <input value={value} onChange={(e) => setValue(e.target.value)} />; }
What is the role of ReactDOM.createRoot in React 18?- Type: Conceptual - Expected Answer: createRoot enables concurrent rendering features in React 18, replacing ReactDOM.render.
How do you implement a custom form library in React?- Type: Coding Challenge - Expected Answer:
function useForm(initialValues) { const [values, setValues] = useState(initialValues); const handleChange = (e) => { setValues({ ...values, [e.target.name]: e.target.value }); }; return { values, handleChange }; }
What are the performance implications of large component trees?- Type: Performance - Expected Answer: Large trees can slow rendering; optimize with memoization, lazy loading, and component splitting.
How do you implement a typeahead search in React?- Type: Coding Challenge - Expected Answer:
function Typeahead({ suggestions }) { const [query, setQuery] = useState(''); const filtered = suggestions.filter((s) => s.includes(query)); return ( <div> <input value={query} onChange={(e) => setQuery(e.target.value)} /> <ul> {filtered.map((s) => ( <li key={s}>{s}</li> ))} </ul> </div> ); }
What is the role of useDeferredValue in React 18?- Type: Conceptual - Expected Answer: useDeferredValue defers non-critical updates to improve responsiveness.
How do you handle authentication in a React app?- Type: Scenario-Based - Expected Answer: Use Context API or Redux to manage auth state, with protected routes via React Router.
What is the difference between useEffect and useLayoutEffect?- Type: Conceptual - Expected Answer: useLayoutEffect runs synchronously before painting, ideal for DOM measurements.
How do you implement a custom animation in React?- Type: Coding Challenge - Expected Answer: Use libraries like framer-motion or CSS animations with React state. - Example:
function FadeIn() { const [isVisible, setIsVisible] = useState(false); return ( <div style={{ opacity: isVisible ? 1 : 0, transition: 'opacity 1s' }}> <button onClick={() => setIsVisible(!isVisible)}>Toggle</button> </div> ); }
What are the challenges of server-side rendering?- Type: Conceptual - Expected Answer: Challenges include hydration mismatches, increased server load, and complex data fetching.
How do you implement a reusable data table component?- Type: Coding Challenge - Expected Answer:
function DataTable({ columns, data }) { return ( <table> <thead> <tr>{columns.map((col) => <th key={col}>{col}</th>)}</tr> </thead> <tbody> {data.map((row, i) => ( <tr key={i}> {columns.map((col) => <td key={col}>{row[col]}</td>)} </tr> ))} </tbody> </table> ); }
What is the role of React.Profiler?- Type: Conceptual - Expected Answer: React.Profiler measures rendering performance for optimization.
How do you handle internationalization (i18n) in React?- Type: Practical - Expected Answer: Use libraries like react-i18next for translations. - Example:
import { useTranslation } from 'react-i18next'; function App() { const { t } = useTranslation(); return <h1>{t('welcome')}</h1>; }
What is the difference between useState and Redux?- Type: Conceptual - Expected Answer: useState is for local state, while Redux manages global state with a single store.
How do you implement a custom hook for debouncing?- Type: Coding Challenge - Expected Answer:
function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => setDebouncedValue(value), delay); return () => clearTimeout(handler); }, [value, delay]); return debouncedValue; }
What is the role of useSyncExternalStore in React 18?- Type: Conceptual - Expected Answer: useSyncExternalStore integrates external stores with React’s concurrent rendering.
How do you optimize a React app for SEO?- Type: Practical - Expected Answer: Use SSR with Next.js, add meta tags, and ensure proper indexing.
How do you implement a custom tooltip component?- Type: Coding Challenge - Expected Answer:
function Tooltip({ text, children }) { const [show, setShow] = useState(false); return ( <div onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}> {children} {show && <div className="tooltip">{text}</div>} </div> ); }
What are the benefits of using React Query for data fetching?- Type: Conceptual - Expected Answer: React Query simplifies data fetching, caching, and synchronization with the server.
How do you implement a custom hook for media queries?- Type: Coding Challenge - Expected Answer:
function useMediaQuery(query) { const [matches, setMatches] = useState(false); useEffect(() => { const media = window.matchMedia(query); setMatches(media.matches); const listener = () => setMatches(media.matches); media.addListener(listener); return () => media.removeListener(listener); }, [query]); return matches; }
What is the role of useReducer in complex forms?- Type: Practical - Expected Answer: useReducer manages complex form state with multiple fields and actions. - Example:
function Form() { const [state, dispatch] = useReducer(formReducer, { name: '', email: '' }); return ( <form> <input value={state.name} onChange={(e) => dispatch({ type: 'update', field: 'name', value: e.target.value })} /> </form> ); }
How do you handle performance issues in Redux?- Type: Performance - Expected Answer: Use memoized selectors, normalize state, and avoid frequent updates.
What is the role of React.StrictMode in testing?- Type: Conceptual - Expected Answer: It detects potential issues like unsafe lifecycle methods and double-renders in development.
How do you implement a custom hook for form validation?- Type: Coding Challenge - Expected Answer:
function useFormValidation(initialState) { const [values, setValues] = useState(initialState); const [errors, setErrors] = useState({}); const validate = (name, value) => { if (!value) return `${name} is required`; return ''; }; const handleChange = (e) => { const { name, value } = e.target; setValues({ ...values, [name]: value }); setErrors({ ...errors, [name]: validate(name, value) }); }; return { values, errors, handleChange }; }
What is the difference between useMemo and useCallback?- Type: Conceptual - Expected Answer: useMemo memoizes values, while useCallback memoizes functions.
How do you implement a virtualized list in React?- Type: Performance - Expected Answer: Use react-window or react-virtualized for rendering large lists efficiently. - Example:
import { FixedSizeList } from 'react-window'; function VirtualList({ items }) { return ( <FixedSizeList height={400} width={300} itemCount={items.length} itemSize={35}> {({ index, style }) => <div style={style}>{items[index]}</div>} </FixedSizeList> ); }
How do you handle cross-browser compatibility in React?- Type: Practical - Expected Answer: Use polyfills, normalize.css, and test across browsers with tools like BrowserStack.
What is the role of useEffect cleanup functions?- Type: Conceptual - Expected Answer: Cleanup functions prevent memory leaks by removing event listeners or cancelling subscriptions.
How do you implement a custom hook for throttling?- Type: Coding Challenge - Expected Answer:
function useThrottle(value, limit) { const [throttledValue, setThrottledValue] = useState(value); useEffect(() => { const handler = setTimeout(() => setThrottledValue(value), limit); return () => clearTimeout(handler); }, [value, limit]); return throttledValue; }
What are the challenges of using Context API for large apps?- Type: Conceptual - Expected Answer: Context API can cause unnecessary re-renders and lacks advanced features like Redux middleware.
How do you implement a reusable accordion component?- Type: Coding Challenge - Expected Answer:
function Accordion({ items }) { const [openIndex, setOpenIndex] = useState(null); return ( <div> {items.map((item, index) => ( <div key={index}> <button onClick={() => setOpenIndex(openIndex === index ? null : index)}> {item.title} </button> {openIndex === index && <div>{item.content}</div>} </div> ))} </div> ); }
What is the role of useLayoutEffect in animations?- Type: Conceptual - Expected Answer: useLayoutEffect ensures animations run before browser painting, avoiding visual glitches.
How do you implement a custom hook for local storage?- Type: Coding Challenge - Expected Answer:
function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => localStorage.getItem(key) || initialValue); useEffect(() => { localStorage.setItem(key, value); }, [key, value]); return [value, setValue]; }
What is the difference between useReducer and Redux?- Type: Conceptual - Expected Answer: useReducer is for local state, while Redux manages global state with middleware and dev tools.
How do you implement a custom hook for window scroll position?- Type: Coding Challenge - Expected Answer:
function useScrollPosition() { const [scroll, setScroll] = useState(0); useEffect(() => { const handleScroll = () => setScroll(window.scrollY); window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); return scroll; }
What are the benefits of using React Suspense for data fetching?- Type: Conceptual - Expected Answer: Suspense simplifies async data handling and improves user experience with fallbacks.
How do you implement a custom hook for geolocation?- Type: Coding Challenge - Expected Answer:
function useGeolocation() { const [position, setPosition] = useState(null); useEffect(() => { navigator.geolocation.getCurrentPosition((pos) => setPosition(pos.coords)); }, []); return position; }
What is the role of useErrorBoundary in React 18?- Type: Conceptual - Expected Answer: useErrorBoundary handles errors in functional components, similar to class-based error boundaries.
How do you implement a custom hook for online/offline status?- Type: Coding Challenge - Expected Answer:
function useOnlineStatus() { const [isOnline, setIsOnline] = useState(navigator.onLine); useEffect(() => { const handleStatus = () => setIsOnline(navigator.onLine); window.addEventListener('online', handleStatus); window.addEventListener('offline', handleStatus); return () => { window.removeEventListener('online', handleStatus); window.removeEventListener('offline', handleStatus); }; }, []); return isOnline; }
What are the challenges of using React with micro-frontends?- Type: Conceptual - Expected Answer: Challenges include module federation, state sharing, and consistent styling across teams.
How do you implement a custom hook for mouse position?- Type: Coding Challenge - Expected Answer:
function useMousePosition() { const [position, setPosition] = useState({ x: 0, y: 0 }); useEffect(() => { const handleMouseMove = (e) => setPosition({ x: e.clientX, y: e.clientY }); window.addEventListener('mousemove', handleMouseMove); return () => window.removeEventListener('mousemove', handleMouseMove); }, []); return position; }
How do you handle large-scale form state management?- Type: Scenario-Based - Expected Answer: Use useReducer or libraries like Formik for complex form state and validation.
What is the role of React.ConcurrentMode in React 18?- Type: Conceptual - Expected Answer: Concurrent Mode enables features like time-slicing and prioritized rendering for better UX.
How do you implement a custom hook for clipboard access?- Type: Coding Challenge - Expected Answer:
function useClipboard() { const copy = async (text) => { await navigator.clipboard.writeText(text); }; return copy; }
What are the trade-offs of using Redux Toolkit vs. plain Redux?- Type: Conceptual - Expected Answer: Redux Toolkit reduces boilerplate with utilities like createSlice, but may add bundle size.
How do you implement a custom hook for animation frame?- Type: Coding Challenge - Expected Answer:
function useAnimationFrame(callback) { useEffect(() => { let id; const animate = () => { callback(); id = requestAnimationFrame(animate); }; id = requestAnimationFrame(animate); return () => cancelAnimationFrame(id); }, [callback]); }
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam