1. What is React?
Answer: React is a JavaScript library developed by Facebook for building user interfaces, particularly single-page applications. It allows developers to create reusable UI components and manage the state of those components efficiently.
Example: A simple React component:
import React from 'react'; class HelloWorld extends React.Component { render() { return <h1>Hello, World!</h1>; } } export default HelloWorld;
2. What are components in React?
Answer: Components are the building blocks of a React application. They are JavaScript functions or classes that optionally accept inputs (called “props”) and return React elements describing what should appear on the screen.
Example:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } export default Welcome;
3. What is the difference between state and props?
Answer:
- Props: Short for properties, they are read-only and passed from parent to child components. They are used to configure a component.
- State: A component’s local state is managed within the component and can be changed using
setState
. It is mutable and used for managing data that changes over time.
Example:
// Props Example function Greeting(props) { return <h1>Hello, {props.name}</h1>; } // State Example class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }
4. What is JSX?
Answer: JSX stands for JavaScript XML. It is a syntax extension for JavaScript that looks similar to HTML. JSX allows developers to write elements and components in a more readable and concise manner.
Example:
const element = <h1>Hello, world!</h1>;
5. How do you handle events in React?
Answer: Events in React are handled similarly to native HTML but with some syntactic differences. In React, you use camelCase syntax for event names and pass a function as the event handler.
Example:
class MyComponent extends React.Component { handleClick = () => { alert('Button clicked!'); }; render() { return <button onClick={this.handleClick}>Click Me</button>; } }
6. What is the virtual DOM?
Answer: The virtual DOM is a lightweight representation of the real DOM. React maintains a virtual DOM to improve performance by minimizing direct manipulations of the real DOM. When a component’s state or props change, React updates the virtual DOM first, compares it with the previous version, and then updates only the necessary parts of the real DOM.
Example:
const oldVdom = <div><p>Old Text</p></div>; const newVdom = <div><p>New Text</p></div>; // React updates only the <p> element in the real DOM
7. What are React hooks?
Answer: React hooks are functions that let you use state and other React features without writing a class. Common hooks include useState
, useEffect
, and useContext
.
Example:
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
8. What is useState
?
Answer: useState
is a hook that lets you add state to functional components. It returns an array with two elements: the current state and a function to update it.
Example:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
9. What is useEffect
?
Answer: useEffect
is a hook that lets you perform side effects in functional components. It is used for operations like data fetching, subscriptions, or manually changing the DOM.
Example:
import React, { useEffect, useState } from 'react'; function FetchData() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Empty array means this effect runs once after the initial render return <div>{data ? data.message : 'Loading...'}</div>; }
10. What is the context API?
Answer: The Context API is a feature in React that allows you to share state between components without having to pass props down manually through every level of the component tree.
Example:
import React, { createContext, useState, useContext } from 'react'; const ThemeContext = createContext(); function ThemedComponent() { const theme = useContext(ThemeContext); return <div style={{ background: theme.background, color: theme.color }}>Themed Component</div>; } function App() { const [theme, setTheme] = useState({ background: 'black', color: 'white' }); return ( <ThemeContext.Provider value={theme}> <ThemedComponent /> </ThemeContext.Provider> ); }
11. What is a higher-order component (HOC)?
Answer: A higher-order component (HOC) is a function that takes a component and returns a new component with additional props or behavior. HOCs are used for code reuse and composition.
Example:
function withLoadingIndicator(WrappedComponent) { return function WithLoadingIndicator(props) { return props.isLoading ? <p>Loading...</p> : <WrappedComponent {...props} />; }; }
12. How do you optimize performance in React?
Answer: Performance can be optimized in React by:
- Using
React.memo
for functional components. - Using
shouldComponentUpdate
orPureComponent
for class components. - Lazy loading components with
React.lazy
andSuspense
. - Memoizing expensive calculations with
useMemo
. - Debouncing or throttling expensive operations.
Example:
import React, { memo } from 'react'; const ExpensiveComponent = memo(function ExpensiveComponent(props) { // component logic });
13. What is React Router?
Answer: React Router is a library used for routing in React applications. It allows you to define routes and navigate between different views or pages in a single-page application.
Example:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; function App() { return ( <Router> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); }
14. What is Redux?
Answer: Redux is a state management library for JavaScript applications. It helps manage application state in a predictable manner using a single store and actions to update the state.
Example:
import { createStore } from 'redux'; const initialState = { count: 0 }; function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; default: return state; } } const store = createStore(reducer);
15. How does ReactDOM.render
work?
Answer: ReactDOM.render
is a method that renders a React element into a DOM node. It takes two arguments: the React element and the DOM node where the element should be rendered.
Example:
import React from 'react'; import ReactDOM from 'react-dom'; const element = <h1>Hello, world!</h1>; ReactDOM.render(element, document.getElementById('root'));
16. What is useReducer
?
Answer: useReducer
is a hook for managing complex state logic in functional components. It is similar to useState
but provides more control for state updates.
Example:
import React, { useReducer } from 'react'; const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error (); } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> Count: {state.count} <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); }
17. What are controlled components?
Answer: Controlled components are form elements whose value is controlled by the React component’s state. The state of the component drives the value of the form element.
Example:
import React, { useState } from 'react'; function ControlledForm() { const [value, setValue] = useState(''); const handleChange = (e) => setValue(e.target.value); return ( <form> <input type="text" value={value} onChange={handleChange} /> </form> ); }
18. What are uncontrolled components?
Answer: Uncontrolled components are form elements that manage their own state internally, and you access their values using refs instead of state.
Example:
import React, { useRef } from 'react'; function UncontrolledForm() { const inputRef = useRef(null); const handleSubmit = (e) => { e.preventDefault(); alert('A name was submitted: ' + inputRef.current.value); }; return ( <form onSubmit={handleSubmit}> <input type="text" ref={inputRef} /> <button type="submit">Submit</button> </form> ); }
19. What is React.StrictMode
?
Answer: React.StrictMode
is a wrapper component that helps find problems in an application during development. It activates additional checks and warnings for its descendants.
Example:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
20. What is React.Fragment
?
Answer: React.Fragment
is a component that lets you group a list of children without adding extra nodes to the DOM.
Example:
import React from 'react'; function List() { return ( <React.Fragment> <li>Item 1</li> <li>Item 2</li> </React.Fragment> ); }
21. What is create-react-app
?
Answer: create-react-app
is a command-line tool that sets up a new React project with a sensible default configuration, including build tools, a development server, and more.
Example:
npx create-react-app my-app cd my-app npm start
22. What are the lifecycle methods in React?
Answer: Lifecycle methods are special methods in class components that are called at different stages of a component’s lifecycle. They include componentDidMount
, componentDidUpdate
, componentWillUnmount
, etc.
Example:
class MyComponent extends React.Component { componentDidMount() { console.log('Component mounted'); } componentDidUpdate(prevProps, prevState) { console.log('Component updated'); } componentWillUnmount() { console.log('Component will unmount'); } render() { return <div>My Component</div>; } }
23. What is React.lazy
and Suspense
?
Answer: React.lazy
is a function that lets you dynamically import components, which can be used with Suspense
to handle loading states. This is useful for code splitting and lazy loading components.
Example:
import React, { Suspense, lazy } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); }
24. What is shouldComponentUpdate
?
Answer: shouldComponentUpdate
is a lifecycle method in class components that determines whether a component should re-render or not. It helps optimize performance by preventing unnecessary renders.
Example:
class MyComponent extends React.Component { shouldComponentUpdate(nextProps, nextState) { return nextProps.someValue !== this.props.someValue; } render() { return <div>{this.props.someValue}</div>; } }
25. What is React.memo
?
Answer: React.memo
is a higher-order component that memoizes a functional component, preventing unnecessary re-renders if the props have not changed.
Example:
import React, { memo } from 'react'; const MyComponent = memo((props) => { return <div>{props.value}</div>; });
26. How do you pass data between components?
Answer: Data is usually passed between components using props. For more complex scenarios, you can use context, state management libraries like Redux, or callback functions.
Example:
// Parent component function Parent() { const data = 'Hello, World!'; return <Child data={data} />; } // Child component function Child(props) { return <div>{props.data}</div>; }
27. What is useCallback
?
Answer: useCallback
is a hook that returns a memoized callback function. It is used to optimize performance by preventing functions from being recreated on every render.
Example:
import React, { useCallback, useState } from 'react'; function MyComponent() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { setCount(count + 1); }, [count]); return <button onClick={handleClick}>Click me</button>; }
28. What is useMemo
?
Answer: useMemo
is a hook that returns a memoized value. It is used to optimize performance by preventing expensive calculations from being re-computed on every render.
Example:
import React, { useMemo, useState } from 'react'; function MyComponent() { const [count, setCount] = useState(0); const computedValue = useMemo(() => { // Expensive calculation return count * 2; }, [count]); return <div>{computedValue}</div>; }
29. What is useContext
?
Answer: useContext
is a hook that lets you access the context value in a functional component. It is used to consume context created with React.createContext
.
Example:
import React, { createContext, useContext } from 'react'; const ThemeContext = createContext('light'); function ThemedComponent() { const theme = useContext(ThemeContext); return <div>Current theme: {theme}</div>; } function App() { return ( <ThemeContext.Provider value="dark"> <ThemedComponent /> </ThemeContext.Provider> ); }
30. What are error boundaries?
Answer: Error boundaries are components that catch JavaScript errors anywhere in their child component tree and log those errors. They also display a fallback UI instead of crashing the entire app.
Example:
import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, info) { console.error('Error caught:', error, info); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
31. What is forwardRef
?
Answer: forwardRef
is a React function that allows you to forward refs to child components. It’s useful when you need to access the DOM node or component instance in a parent component.
Example:
import React, { forwardRef } from 'react'; const FancyInput = forwardRef((props, ref) => ( <input ref={ref} {...props} /> )); function App() { const inputRef = React.createRef(); return ( <div> <FancyInput ref={inputRef} /> </div> ); }
32. What is the purpose of componentDidCatch
?
Answer: componentDidCatch
is a lifecycle method used in error boundaries to catch errors that occur during rendering, in lifecycle methods, or in constructors of the whole tree beneath the component.
Example:
componentDidCatch(error, info) { // Handle the error }
33. What are portals?
Answer: Portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component.
Example:
import React from 'react'; import ReactDOM from 'react-dom'; function Modal({ children }) { return ReactDOM.createPortal( <div className="modal">{children}</div>, document.getElementById('modal-root') ); }
34.
How does React handle form submissions?
Answer: React handles form submissions by defining an onSubmit
event handler on the form element and controlling the form’s state.
Example:
import React, { useState } from 'react'; function MyForm() { const [inputValue, setInputValue] = useState(''); const handleSubmit = (event) => { event.preventDefault(); alert('Form submitted with value: ' + inputValue); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <button type="submit">Submit</button> </form> ); }
35. What is the key
prop in React?
Answer: The key
prop is used to uniquely identify elements in a list. It helps React optimize rendering by identifying which items have changed, been added, or removed.
Example:
function List({ items }) { return ( <ul> {items.map((item) => ( <li key={item.id}>{item.value}</li> ))} </ul> ); }
36. How do you handle dynamic imports in React?
Answer: Dynamic imports in React can be handled using React.lazy
and Suspense
for code splitting.
Example:
const LazyComponent = React.lazy(() => import('./LazyComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); }
37. What is useImperativeHandle
?
Answer: useImperativeHandle
is a hook that allows you to customize the instance value that is exposed when using ref
with forwardRef
.
Example:
import React, { forwardRef, useImperativeHandle, useRef } from 'react'; const FancyInput = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} {...props} />; }); function App() { const inputRef = useRef(); return ( <div> <FancyInput ref={inputRef} /> <button onClick={() => inputRef.current.focus()}>Focus Input</button> </div> ); }
38. What is React.StrictMode
and how does it differ from React.Fragment
?
Answer: React.StrictMode
is used to identify potential problems in an application by activating additional checks and warnings during development. It does not render any extra DOM elements. React.Fragment
, on the other hand, is used to group elements without adding extra nodes to the DOM.
Example:
// React.StrictMode <React.StrictMode> <App /> </React.StrictMode> // React.Fragment <React.Fragment> <Child1 /> <Child2 /> </React.Fragment>
39. What is useLayoutEffect
?
Answer: useLayoutEffect
is similar to useEffect
, but it fires synchronously after all DOM mutations. It’s useful for reading layout from the DOM and synchronously re-rendering.
Example:
import React, { useLayoutEffect, useRef } from 'react'; function LayoutEffectExample() { const divRef = useRef(); useLayoutEffect(() => { console.log(divRef.current.getBoundingClientRect()); }, []); return <div ref={divRef}>Hello, world!</div>; }
40. What is useDebugValue
?
Answer: useDebugValue
is a hook used to display a label for custom hooks in React DevTools. It helps with debugging by showing additional information.
Example:
import { useDebugValue } from 'react'; function useCustomHook(value) { useDebugValue(value ? 'Value is true' : 'Value is false'); return value; }
41. What is ReactDOMServer
?
Answer: ReactDOMServer
is a package for server-side rendering of React components. It allows you to render React components to static HTML on the server.
Example:
import React from 'react'; import ReactDOMServer from 'react-dom/server'; const element = <h1>Hello, world!</h1>; const html = ReactDOMServer.renderToString(element); console.log(html); // Outputs: <h1>Hello, world!</h1>
42. What is useTransition
?
Answer: useTransition
is a hook that lets you manage state transitions in a way that keeps the interface responsive. It is part of the experimental features in React.
Example:
import React, { useState, useTransition } from 'react'; function App() { const [isPending, startTransition] = useTransition(); const [inputValue, setInputValue] = useState(''); const handleChange = (event) => { startTransition(() => { setInputValue(event.target.value); }); }; return ( <div> <input type="text" value={inputValue} onChange={handleChange} /> {isPending && <p>Loading...</p>} </div> ); }
43. What is React.StrictMode
used for?
Answer: React.StrictMode
is a tool for identifying components with unsafe lifecycle methods, deprecated APIs, and other issues. It helps with detecting potential problems in the application.
Example:
<React.StrictMode> <App /> </React.StrictMode>
44. How do you handle authentication in React?
Answer: Authentication can be handled using context for managing user state, or by integrating with authentication libraries and services. Routes can be protected based on authentication status.
Example:
import React, { createContext, useState, useContext } from 'react'; import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'; const AuthContext = createContext(); function AuthProvider({ children }) { const [isAuthenticated, setIsAuthenticated] = useState(false); const login = () => setIsAuthenticated(true); const logout = () => setIsAuthenticated(false); return ( <AuthContext.Provider value={{ isAuthenticated, login, logout }}> {children} </AuthContext.Provider> ); } function PrivateRoute({ component: Component, ...rest }) { const { isAuthenticated } = useContext(AuthContext); return ( <Route {...rest} render={(props) => isAuthenticated ? <Component {...props} /> : <Redirect to="/login" /> } /> ); } function App() { const { login, logout, isAuthenticated } = useContext(AuthContext); return ( <Router> <Route path="/login" render={() => <button onClick={login}>Login</button>} /> <PrivateRoute path="/protected" component={() => <button onClick={logout}>Logout</button>} /> </Router> ); }
45. What are some best practices for writing React components?
Answer:
- Keep components small and focused.
- Use functional components and hooks when possible.
- Use prop types or TypeScript for type checking.
- Use
useEffect
anduseCallback
wisely to manage side effects and memoize functions. - Use
React.memo
to prevent unnecessary re-renders. - Write reusable components and avoid duplicating code.
46. How do you manage side effects in functional components?
Answer: Side effects in functional components are managed using the useEffect
hook. It can be used for data fetching, subscriptions, or manual DOM manipulations.
Example:
import React, { useEffect, useState } from 'react'; function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Empty dependency array means this effect runs once return <div>{data ? data.message : 'Loading...'}</div>; }
47. What are custom hooks?
Answer: Custom hooks are JavaScript functions that start with use
and allow you to reuse stateful logic between components. They encapsulate and share logic without changing the component hierarchy.
Example:
import { useState, useEffect } from 'react'; function useWindowWidth() { const [windowWidth, setWindowWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => setWindowWidth(window.innerWidth); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return windowWidth; }
48. How do you handle asynchronous operations in React?
Answer: Asynchronous operations are often handled using the useEffect
hook for side effects, async/await
syntax for promises, and useReducer
for complex state management.
Example:
import React, { useState, useEffect } from 'react'; function AsyncComponent() { const [data, setData] = useState(null); useEffect (() => { const fetchData = async () => { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); }; fetchData(); }, []); return <div>{data ? data.message : 'Loading...'}</div>; }
49. What is the purpose of the useEffect
hook?
Answer: The useEffect
hook is used for managing side effects in functional components. It can handle tasks like data fetching, subscriptions, and manual DOM manipulations.
Example:
import React, { useEffect, useState } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Dependency array return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
50. How do you optimize React performance?
Answer: Performance optimization in React can be achieved by:
- Using
React.memo
to prevent unnecessary re-renders. - Using
useCallback
anduseMemo
to memoize functions and values. - Code splitting with
React.lazy
andSuspense
. - Using
PureComponent
for class components. - Profiling with React DevTools to identify performance bottlenecks.
Example:
import React, { useCallback, useState } from 'react'; const MemoizedComponent = React.memo(({ onClick }) => { console.log('Rendering MemoizedComponent'); return <button onClick={onClick}>Click me</button>; }); function ParentComponent() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { setCount(count + 1); }, [count]); return ( <div> <MemoizedComponent onClick={handleClick} /> <p>Count: {count}</p> </div> ); }