Top 50 React Interview Questions: Functional Components & Modern Best Practices
1. What is React?
React is a JavaScript library for building user interfaces. It allows developers to create reusable UI components and efficiently update and render them when data changes.
2. What is the history behind React evolution?
React was created by Jordan Walke, a software engineer at Facebook, in 2011. It was first deployed on Facebook's newsfeed in 2011 and later open-sourced in May 2013. Since then, it has grown to become one of the most popular front-end libraries.
3. What are the major features of React?
- Virtual DOM for efficient updates
- JSX syntax
- Component-based architecture
- Unidirectional data flow
- React Hooks (since React 16.8)
- Server-side rendering
4. What is JSX?
JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It's used with React to describe what the UI should look like.
Example:
function Greeting({ name }) { return <h1>Hello, {name}!</h1>; }
5. What is the difference between Element and Component?
An Element is a plain object describing what you want to appear on the screen. A Component is a function or class that accepts inputs (called "props") and returns a React element.
6. How to create components in React?
In modern React, functional components are the preferred way to create components:
function Welcome({ name }) { return <h1>Hello, {name}</h1>; }
7. When to use a Class Component over a Function Component?
With the introduction of Hooks, functional components can now handle state and lifecycle methods. Class components are mainly used for legacy code or when you need to use error boundaries.
8. What are Pure Components?
Pure Components are components that only re-render when their props or state change. In functional components, you can achieve this using React.memo():
const PureComponent = React.memo(function MyComponent(props) { // render using props });
9. What is state in React?
State is an object that holds data that may change over time. In functional components, we use the useState hook to manage state:
function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
10. What are props in React?
Props (short for properties) are inputs to a React component. They are passed down from a parent component to a child component:
function Welcome({ name }) { return <h1>Hello, {name}</h1>; } function App() { return <Welcome name="Sara" />; }
11. What is the difference between state and props?
Props are passed to the component (similar to function parameters) whereas state is managed within the component (similar to variables declared within a function).
12. What is the difference between HTML and React event handling?
In React, event names use camelCase and you pass a function as the event handler, rather than a string:
function Button() { const handleClick = () => console.log('Clicked!'); return <button onClick={handleClick}>Click me</button>; }
13. What are synthetic events in React?
Synthetic events are React's cross-browser wrapper around the browser's native event. They have the same interface as native events, but work identically across all browsers.
14. What are inline conditional expressions?
In JSX, you can use inline conditions to conditionally render elements:
function Greeting({ isLoggedIn }) { return ( <div> {isLoggedIn ? <UserGreeting /> : <GuestGreeting />} </div> ); }
15. What is a "key" prop and what is the benefit of using it in arrays of elements?
The "key" prop is a special string attribute used when creating lists of elements. Keys help React identify which items have changed, been added, or been removed.
function NumberList({ numbers }) { return ( <ul> {numbers.map((number) => <li key={number.toString()}>{number}</li> )} </ul> ); }
16. What is Virtual DOM?
The Virtual DOM is a lightweight copy of the actual DOM in memory. React uses it to improve performance by minimizing direct manipulation of the DOM.
17. How does Virtual DOM work?
When state changes in a React component:
- A new virtual DOM is created
- It's compared with the previous virtual DOM (diffing)
- Only the differences are updated in the real DOM
18. What is the difference between Shadow DOM and Virtual DOM?
Shadow DOM is a browser technology for scoping variables and CSS in web components. Virtual DOM is a concept implemented by libraries like React for performance optimization.
19. What is React Fiber?
React Fiber is the new reconciliation engine in React 16. It aims to enable incremental rendering of the virtual DOM.
20. What is the main goal of React Fiber?
The main goals of React Fiber are to increase its suitability for areas like animation, layout, and gestures. It enables features like the ability to pause, abort, or reuse work as new updates come in.
21. What are controlled components?
In a controlled component, form data is handled by the React component's state:
function ControlledInput() { const [value, setValue] = useState(''); return ( <input type="text" value={value} onChange={(e) => setValue(e.target.value)} /> ); }
22. What are uncontrolled components?
Uncontrolled components store their own state internally, and you query the DOM using a ref to find its current value when you need it:
function UncontrolledInput() { const inputRef = useRef(null); const handleSubmit = (e) => { e.preventDefault(); console.log('Input Value:', inputRef.current.value); }; return ( <form onSubmit={handleSubmit}> <input type="text" ref={inputRef} /> <button type="submit">Submit</button> </form> ); }
23. What is the difference between createElement and cloneElement?
createElement is used to create new React elements, while cloneElement is used to clone and modify existing elements.
24. What is Lifting State Up in React?
Lifting state up means moving the state to a common ancestor of components that need it, so that they can share state.
25. What are Higher-Order components?
A Higher-Order Component (HOC) is a function that takes a component and returns a new component with some additional functionality:
function withLogging(WrappedComponent) { return function(props) { console.log('Props:', props); return <WrappedComponent {...props} />; } } const EnhancedComponent = withLogging(MyComponent);
26. What is children prop?
The children prop is a special prop that lets you pass components as data to other components:
function Layout({ children }) { return ( <div> <Header /> {children} <Footer /> </div> ); } function App() { return ( <Layout> <Main /> </Layout> ); }
27. How to write comments in React?
In JSX, comments are written inside curly braces with the /* */ syntax:
function Component() { return ( <div> {/* This is a comment */} <p>This is visible text</p> </div> ); }
28. What is reconciliation?
Reconciliation is the process React uses to update the DOM. When a component's state changes, React creates a new virtual DOM tree, diffs it with the previous one, and then only updates the real DOM with the necessary changes.
29. Does the lazy function support named exports?
No, React.lazy currently only supports default exports. If you want to import a named export, you can create an intermediate module that re-exports it as the default export.
30. Why React uses className over class attribute?
React uses className instead of class for specifying CSS classes because class is a reserved keyword in JavaScript.
function MyComponent() { return <div className="my-class">Hello</div>; }
31. What are fragments?
Fragments let you group a list of children without adding extra nodes to the DOM:
function MyComponent() { return ( <> <ChildA /> <ChildB /> <ChildC /> </> ); }
32. Why fragments are better than container divs?
Fragments don't create an extra DOM node, which can be beneficial for performance and keeps the DOM cleaner.
33. What are portals in React?
Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component:
function Modal({ children }) { return ReactDOM.createPortal( children, document.getElementById('modal-root') ); }
34. What are stateless components?
Stateless components, also known as functional components, are components that don't have their own state. They simply accept props and render UI based on those props.
35. What are stateful components?
Stateful components are components that maintain their own state. With hooks, functional components can also be stateful:
function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
36. How to apply validation on props in React?
You can use PropTypes to validate props:
import PropTypes from 'prop-types'; function MyComponent({ name }) { return <div>{name}</div>; } MyComponent.propTypes = { name: PropTypes.string.isRequired, };
37. What are the advantages of React?
- Virtual DOM for better performance
- Reusable components
- Unidirectional data flow
- Large community and ecosystem
- JSX for easier component writing
- React Native for mobile development
38. What are the limitations of React?
- It's a library, not a full framework
- It can be overwhelming for beginners
- JSX can be a barrier for some developers
- Frequent updates can be hard to keep up with
39. What are the recommended ways for static type checking?
The two most popular ways are:
- PropTypes (built into React)
- TypeScript (a typed superset of JavaScript)
40. What is the use of react-dom package?
The react-dom package provides DOM-specific methods that can be used at the top level of your app, such as ReactDOM.render().
41. What is ReactDOMServer?
ReactDOMServer allows you to render your components to static markup, which is useful for server-side rendering.
42. How to use InnerHtml in React?
You can use the dangerouslySetInnerHTML prop, but be cautious as it can expose your app to XSS attacks:
function MyComponent() { return <div dangerouslySetInnerHTML={{ __html: "<p>Raw HTML</p>" }} />; }
43. How to use styles in React?
You can use inline styles or import CSS files:
function MyComponent() { const style = { color: 'red', fontSize: '16px' }; return <div style={style}>Styled text</div>; }
44. How events are different in React?
React wraps browser events in SyntheticEvent objects, which have a consistent interface across different browsers.
45. What is the impact of indexes as keys?
Using indexes as keys can negatively impact performance and may cause issues with component state when items are reordered.
46. How do you conditionally render components?
You can use JavaScript conditions to render components conditionally:
function MyComponent({ isLoggedIn }) { return ( <div> {isLoggedIn ? <UserGreeting /> : <GuestGreeting />} </div> ); }
47. Why we need to be careful when spreading props on DOM elements?
Spreading props can lead to passing unnecessary props to the DOM, which can cause performance issues or unexpected behavior.
48. How do you memoize a component?
You can use React.memo to memoize a functional component:
const MyComponent = React.memo(function MyComponent(props) { // only rerenders if props change });
49. How you implement Server-Side Rendering or SSR?
SSR can be implemented using ReactDOMServer's renderToString method on the server, and then using ReactDOM.hydrate on the client to attach event listeners.
50. How to enable production mode in React?
When you build your app for production (e.g., with Create React App), it automatically enables production mode. You can also set process.env.NODE_ENV to 'production'.