DEV Community

Softden 2005
Softden 2005

Posted on • Edited on

πŸ“šReactJS Questions and Answers

1. Basic Concepts

Q1: What is React? πŸ€”

A: React is an open-source JavaScript library for building user interfaces, primarily for single-page applications. It allows developers to create large web applications that can change data, without reloading the page.

Q2: What are the main features of React? 🌟

A:

  • Virtual DOM: React creates a virtual representation of the real DOM, which improves performance.
  • Component-based Architecture: UI is divided into reusable components.
  • Unidirectional Data Flow: Data flows in a single direction, making the application easier to understand.

Q3: What is JSX? πŸ“œ

A: JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML elements in JavaScript and placing them in the DOM without createElement().

Q4: Explain the concept of components in React. 🧩

A: Components are the building blocks of a React application. They can be either class-based or functional, encapsulating their structure, behavior, and styling.

Q5: What is the difference between a class component and a functional component? βš™οΈ

A:

  • Class Component: Uses ES6 class syntax, has lifecycle methods, and can maintain internal state.
  • Functional Component: A simpler way to write components as functions, which can use hooks to manage state and side effects.

2. State and Props

Q6: What are props in React? 🎁

A: Props (short for properties) are read-only attributes passed from a parent component to a child component. They allow data to flow in a unidirectional way.

Q7: How do you manage state in React? πŸ“Š

A: State can be managed using:

  • Class Components: By using this.state and this.setState().
  • Functional Components: Using the useState hook.

Q8: Can you explain the useState hook? πŸ”„

A: The useState hook allows functional components to manage state. It returns an array with two elements: the current state and a function to update it.

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

Q9: How do you pass data from parent to child components? πŸ”—

A: Data is passed from parent to child components using props.

<ChildComponent data={parentData} />
Enter fullscreen mode Exit fullscreen mode

Q10: What is the significance of the key prop in React? πŸ”‘

A: The key prop is used to uniquely identify elements in a list. It helps React optimize rendering by tracking which items have changed, added, or removed.

3. Lifecycle Methods

Q11: What are lifecycle methods in React? ⏳

A: Lifecycle methods are hooks that allow developers to run code at specific points in a component’s lifecycle, such as componentDidMount, componentDidUpdate, and componentWillUnmount.

Q12: Can you explain the componentDidMount method? πŸ“…

A: componentDidMount is a lifecycle method called after a component is rendered for the first time. It is often used to fetch data or perform setup operations.

componentDidMount() {
  fetchData();
}
Enter fullscreen mode Exit fullscreen mode

Q13: What is the purpose of componentWillUnmount? πŸ›‘

A: componentWillUnmount is called just before a component is removed from the DOM. It’s commonly used for cleanup tasks, like canceling network requests or removing event listeners.

Q14: How do you handle state updates in lifecycle methods? πŸ”„

A: State updates can be handled in lifecycle methods using this.setState() in class components or the state updater function in hooks for functional components.

Q15: What is the use of the shouldComponentUpdate method? ❓

A: shouldComponentUpdate is a lifecycle method that determines whether a component should re-render. It can be used to optimize performance by preventing unnecessary renders.

4. React Hooks

Q16: What are React Hooks? 🎣

A: Hooks are functions that let you use state and other React features in functional components. They enable functional components to manage state, side effects, and context.

Q17: Explain the useEffect hook. πŸ”„

A: The useEffect hook is used to perform side effects in functional components, such as fetching data or subscribing to events. It runs after every render by default.

useEffect(() => {
  fetchData();
}, [dependency]);
Enter fullscreen mode Exit fullscreen mode

Q18: How do you create a custom hook? πŸ”§

A: A custom hook is a JavaScript function that starts with use and can call other hooks. It allows for reusable logic across components.

function useCounter() {
  const [count, setCount] = useState(0);
  return { count, setCount };
}
Enter fullscreen mode Exit fullscreen mode

Q19: What is the purpose of the useContext hook? 🌍

A: The useContext hook allows you to access the context value directly in functional components, without the need for a Consumer component.

Q20: Explain the useReducer hook. βš–οΈ

A: The useReducer hook is used for managing more complex state logic in a component, similar to Redux. It takes a reducer function and an initial state.

const [state, dispatch] = useReducer(reducer, initialState);
Enter fullscreen mode Exit fullscreen mode

5. Advanced Concepts

Q21: What is Context API in React? 🌐

A: The Context API is a way to share values (like state) between components without having to pass props explicitly through every level of the component tree.

Q22: How do you create a Context? πŸ› οΈ

A: A Context is created using React.createContext(), which returns a Provider and Consumer.

const MyContext = React.createContext();
Enter fullscreen mode Exit fullscreen mode

Q23: Explain how to use the React Router. 🚦

A: React Router is a library for routing in React applications. It allows you to define routes in your application to render different components based on the URL.

<BrowserRouter>
  <Route path="/" component={Home} />
  <Route path="/about" component={About} />
</BrowserRouter>
Enter fullscreen mode Exit fullscreen mode

Q24: What are Higher-Order Components (HOCs)? πŸ”

A: HOCs are functions that take a component and return a new component with additional props or functionality. They are used for cross-cutting concerns like authentication.

Q25: Explain the concept of code splitting in React. πŸ”„

A: Code splitting is a technique to split your application into smaller bundles that can be loaded on demand, improving performance. It can be achieved using dynamic imports and React.lazy.

6. Testing

Q26: How do you test a React component? πŸ§ͺ

A: React components can be tested using libraries like Jest and React Testing Library. They provide utilities for rendering components and asserting their behavior.

Q27: What is shallow rendering? 🌊

A: Shallow rendering is a way to render a component without rendering its child components. It is useful for unit testing by focusing on the component’s output.

const wrapper = shallow(<MyComponent />);
Enter fullscreen mode Exit fullscreen mode

Q28: What are mocks in testing? 🎭

A: Mocks are simulated objects that mimic the behavior of real objects in a controlled way. They are used to isolate components during testing.

Q29: Explain the difference between unit testing and integration testing. πŸ”„

A:

  • Unit Testing: Tests individual components in isolation to ensure they function correctly.
  • Integration Testing: Tests how multiple components or modules work together.

Q30: What is the purpose of the React Testing Library? πŸ“š

A: The React Testing Library provides utilities to test React components by focusing on user interactions and the component’s rendered output rather than implementation details.

7. Performance Optimization

Q31: How can you optimize performance in a React application? πŸš€

A:

  • Memoization: Use React.memo for functional components and PureComponent for class components to prevent unnecessary re-renders.
  • Code Splitting: Load components on demand.
  • Lazy Loading: Load images and resources only when needed.

Q32: What is the use of React.memo? πŸ§˜β€β™‚οΈ

A: React.memo is a higher-order component that memoizes the rendered output of a functional component, preventing re-renders if the props have not changed.

Q33: Explain the significance of the useCallback hook. πŸ”„

A: The useCallback hook returns a memoized version of a callback function that only changes if one of its dependencies has changed, optimizing performance in child components.

const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);
Enter fullscreen mode Exit fullscreen mode

Q34: What is the use of the useMemo hook? πŸ“Š

A: The useMemo hook returns a memoized value that only recalculates if its dependencies change, optimizing performance by preventing expensive calculations on every render.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Enter fullscreen mode Exit fullscreen mode

Q35: How do you handle large lists in React? πŸ“‹

A: When dealing with large lists, consider using techniques like:

  • Windowing: Use libraries like react-window or react-virtualized to only render the visible portion of a list, improving performance by reducing the number of DOM nodes.
  • Pagination: Load and display a subset of the data at a time to minimize the number of rendered elements.
  • Infinite Scroll: Load more items as the user scrolls down the page, providing a seamless experience.
import { FixedSizeList as List } from 'react-window';

const MyList = () => (
  <List
    height={500}
    itemCount={1000}
    itemSize={35}
    width={300}
  >
    {({ index }) => <div>Item {index}</div>}
  </List>
);
Enter fullscreen mode Exit fullscreen mode

8. Forms

Q36: How do you handle forms in React? πŸ“

A: Forms in React can be handled using controlled components, where form data is stored in the component's state and updated via event handlers. You can also use libraries like Formik or React Hook Form for complex forms.

const [inputValue, setInputValue] = useState('');

const handleChange = (event) => {
  setInputValue(event.target.value);
};

return (
  <form>
    <input type="text" value={inputValue} onChange={handleChange} />
  </form>
);
Enter fullscreen mode Exit fullscreen mode

Q37: What is controlled vs uncontrolled component? 🎭

A:

  • Controlled Component: The form element's value is controlled by React state. Its value is set by the state.
  • Uncontrolled Component: The form element maintains its own state, and you can access its value using a ref.

Q38: How do you handle form submission in React? πŸ“€

A: Form submission can be handled by preventing the default behavior of the form and processing the data through an event handler.

const handleSubmit = (event) => {
  event.preventDefault();
  // Process form data
};

return (
  <form onSubmit={handleSubmit}>
    <input type="text" />
    <button type="submit">Submit</button>
  </form>
);
Enter fullscreen mode Exit fullscreen mode

Q39: How do you validate forms in React? βœ…

A: Form validation can be done manually by checking values on submission or by using libraries like Formik or Yup for schema-based validation.

Q40: What are the advantages of using Formik? πŸ“¦

A: Formik simplifies form handling in React by managing form state, validation, and submission, allowing developers to focus on UI without worrying about boilerplate code.

9. React Router

Q41: What is React Router? 🚦

A: React Router is a library that enables routing in React applications, allowing navigation between different components and views based on the URL.

Q42: How do you set up a basic router? πŸ”„

A: You set up a basic router using BrowserRouter, Route, and Switch components.

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const App = () => (
  <Router>
    <Switch>
      <Route path="/" component={Home} />
      <Route path="/about" component={About} />
    </Switch>
  </Router>
);
Enter fullscreen mode Exit fullscreen mode

Q43: What are nested routes in React Router? πŸ•ΈοΈ

A: Nested routes allow you to render components inside other components based on the route. You can define routes within other route components.

<Route path="/dashboard">
  <Dashboard>
    <Route path="/settings" component={Settings} />
  </Dashboard>
</Route>
Enter fullscreen mode Exit fullscreen mode

Q44: How do you pass props to routed components? πŸ“¬

A: Props can be passed to routed components using the render prop or by using the children prop.

<Route path="/user" render={(props) => <User {...props} user={user} />} />
Enter fullscreen mode Exit fullscreen mode

Q45: What is the purpose of the useHistory hook? πŸ›€οΈ

A: The useHistory hook allows you to programmatically navigate between routes, access the history instance, and manipulate the session history.

const history = useHistory();
const handleClick = () => {
  history.push('/new-route');
};
Enter fullscreen mode Exit fullscreen mode

10. Redux

Q46: What is Redux? πŸ”„

A: Redux is a state management library for JavaScript applications, often used with React. It allows for centralized state management and predictable state transitions.

Q47: How does Redux work? βš™οΈ

A: Redux works with three core principles:

  • Single Source of Truth: The entire application state is stored in a single store.
  • State is Read-Only: The only way to change the state is by dispatching actions.
  • Changes are Made with Pure Functions: Reducers are pure functions that take the current state and an action and return a new state.

Q48: Explain the role of actions in Redux. πŸ“œ

A: Actions are plain JavaScript objects that describe a change in the application. Each action must have a type property that indicates the type of action being performed.

const ADD_TODO = 'ADD_TODO';
const addTodo = (todo) => ({
  type: ADD_TODO,
  payload: todo,
});
Enter fullscreen mode Exit fullscreen mode

Q49: What are reducers in Redux? πŸ“‰

A: Reducers are pure functions that take the previous state and an action as arguments and return a new state. They describe how the state changes in response to actions.

const todosReducer = (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return [...state, action.payload];
    default:
      return state;
  }
};
Enter fullscreen mode Exit fullscreen mode

Q50: How do you connect Redux with React? πŸ”—

A: You can connect Redux with React using the react-redux library, specifically the Provider component to wrap your application and the connect function or useSelector and useDispatch hooks to access the store.

import { Provider } from 'react-redux';
import { createStore } from 'redux';

const store = createStore(reducer);

const App = () => (
  <Provider store={store}>
    <MyComponent />
  </Provider>
);
Enter fullscreen mode Exit fullscreen mode

11. API Integration

Q51: How do you make API calls in React? 🌐

A: API calls in React can be made using fetch, axios, or other libraries inside lifecycle methods or hooks like useEffect.

useEffect(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => setData(data));
}, []);
Enter fullscreen mode Exit fullscreen mode

Q52: What is the purpose of the async/await syntax? ⏳

A: The async/await syntax allows you to write asynchronous code in a more readable manner, making it look synchronous. It simplifies the handling of promises.

const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  setData(data);
};
Enter fullscreen mode Exit fullscreen mode

Q53: How do you handle errors in API calls? ❌

A: Errors can be handled using try/catch blocks with async/await or using .catch() with promises to catch and manage errors gracefully.

const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('Network response was not ok');
    const data = await response.json();
    setData(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
};
Enter fullscreen mode Exit fullscreen mode

Q54: What is the role of Axios in API calls? πŸ“¦

A: Axios is a promise-based HTTP client for JavaScript that simplifies making API requests. It supports request and response interception, automatic JSON data transformation, and can be configured globally.

import axios from 'axios';

const fetchData = () => {
  axios.get('https://api.example.com/data')
    .then(response => setData(response.data))
    .catch(error => console.error('Error:', error));
};
Enter fullscreen mode Exit fullscreen mode

Q55: How can you handle loading states in API calls? ⏳

A: Loading states can be managed by setting a state variable (e.g., isLoading) to true before the API call and resetting it to false after the data is fetched or an error occurs.

const [isLoading, setIsLoading] = useState(false);

const fetchData = async () => {
  setIsLoading(true);
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    setData(data);
  } finally {
    setIsLoading(false);
  }
};
Enter fullscreen mode Exit fullscreen mode

12. Styling

Q56: How do you style React components? 🎨

A: React components can be styled using:

  • CSS Stylesheets: Regular CSS files linked in the project.
  • Inline Styles: Using the style attribute with JavaScript objects.
  • CSS Modules: Scoped CSS that prevents class name collisions.
  • Styled-components: A library for writing CSS-in-JS.

Q57: What are CSS Modules? πŸ“š

A: CSS Modules are a way to scope CSS by generating unique class names. This prevents styles from leaking into other components.

/* styles.module.css */
.button {
  background-color: blue;
}
Enter fullscreen mode Exit fullscreen mode
import styles from './styles.module.css';

const MyComponent = () => <button className={styles.button}>Click me</button>;
Enter fullscreen mode Exit fullscreen mode

Q58: What is styled-components? πŸ–ŒοΈ

A: Styled-components is a library that allows you to write CSS styles in JavaScript. It uses tagged template literals to style components dynamically.

import styled from 'styled-components';

const Button = styled.button`
  background-color: blue;
  color: white;
`;

const MyComponent = () => <Button>Click me</Button>;
Enter fullscreen mode Exit fullscreen mode

Q59: How can you implement responsive design in React? πŸ“±

A: Responsive design can be achieved using:

  • CSS Media Queries: To apply different styles based on the screen size.
  • Flexbox/Grid Layouts: For fluid layouts that adapt to different screen sizes.
  • Responsive Libraries: Such as Bootstrap or Material-UI for pre-built responsive components.

Q60: What is the significance of the className attribute in React? 🏷️

A: In React, className is used instead of class to apply CSS styles to elements, as class is a reserved keyword in JavaScript.

return <div className="my-class">Hello, world!</div>;
Enter fullscreen mode Exit fullscreen mode

13. Deployment

Q61: How do you deploy a React application? πŸš€

A: React applications can be deployed by building the application using npm run build and then serving the static files using platforms like Netlify, Vercel, or GitHub Pages.

Q62: What is the purpose of the build folder in React? πŸ—οΈ

A: The build folder contains the optimized production version of the React application, including minified JavaScript, CSS files, and static assets.

Q63: How can you optimize a React app for production? πŸ“ˆ

A: Optimization can be done by:

  • Minifying Code: Using tools like Webpack to minimize file sizes.
  • Code Splitting: To load only the necessary parts of the application.
  • Lazy Loading: To load components and routes on demand.

Q64: What is the role of Webpack in a React project? βš™οΈ

A: Webpack is a module bundler that takes modules with dependencies and generates static assets representing those modules. It handles code splitting, asset management, and transpilation with Babel.

Q65: How do you set up environment variables in React? 🌎

A: Environment variables can be set up in a .env file at the root of the project. They should start with REACT_APP_ to be accessible in the application.

REACT_APP_API_URL=https://api.example.com
Enter fullscreen mode Exit fullscreen mode
const apiUrl = process.env.REACT_APP_API_URL;
Enter fullscreen mode Exit fullscreen mode

14. Security

Q66: What are common security risks in React applications? πŸ”’

A: Common security risks include:

  • Cross-Site Scripting (XSS): Malicious scripts injected into the application.
  • Cross-Site Request Forgery (CSRF): Unauthorized commands being transmitted from a user.
  • Insecure Dependencies: Using outdated or vulnerable libraries.

Q67: How can you prevent XSS in React? 🚫

A: Prevent XSS by:

  • Validating and sanitizing user inputs.
  • Avoiding the use of dangerouslySetInnerHTML.
  • Using libraries like DOMPurify to clean HTML.

Q68: What is CSRF and how can you prevent it? πŸ”’

A: CSRF is an attack that tricks the user into submitting unwanted actions. It can be prevented by using anti-CSRF tokens, setting the SameSite attribute on cookies, and validating the origin of requests.

Q69: How do you secure API calls in a React application? πŸ”‘

A: Secure API calls by:

  • Using HTTPS to encrypt data in transit.
  • Implementing authentication and authorization mechanisms (e.g., JWT).
  • Validating and sanitizing inputs on the server side.

Q70: What is content security policy (CSP)? πŸ“œ

A: Content Security Policy (CSP) is a security feature that helps prevent XSS attacks by specifying which sources of content are trustworthy. It restricts the execution of scripts and resources.

15. Best Practices

Q71: What are some best practices for writing React components? πŸ› οΈ

A:

  • Keep components small and focused on a single responsibility.
  • Use prop-types or TypeScript for type checking.
  • Write tests for components to ensure reliability.

Q72: How do you structure a React application? πŸ—οΈ

A: Structure a React application by organizing files based on features or components, separating concerns (e.g., components, styles, tests), and maintaining a clear hierarchy.

Q73: Why is it important to use key prop in lists? πŸ”‘

A: The key prop helps React identify which items have changed, are added, or are removed, improving performance and avoiding issues with component state.

Q74: What is the importance of keeping state local? 🌍

A: Keeping state local to components minimizes unnecessary re-renders, simplifies data flow, and enhances component reusability.

Q75: How can you improve the accessibility of a React application? β™Ώ

A: Improve accessibility by:

  • Using semantic HTML elements.
  • Adding ARIA attributes where necessary.
  • Ensuring proper focus management and keyboard navigation.

16. TypeScript with React

Q76: What is TypeScript? πŸ›‘οΈ

A: TypeScript is a superset of JavaScript that adds static typing to the language, enabling better tooling and catching errors at compile time.

Q77: How do you use TypeScript in a React application? βš™οΈ

A: To use TypeScript in a React application, you can set up a new project with Create React App using the --template typescript option or configure TypeScript manually.

npx create-react-app my-app --template typescript
Enter fullscreen mode Exit fullscreen mode

Q78: What are the benefits of using TypeScript with React? 🎯

A: Benefits include:

  • Improved code quality through static type checking.
  • Enhanced developer experience with better autocompletion and documentation.
  • Easier refactoring due to strong typing.

Q79: How do you define props in a TypeScript React component? πŸ“¦

A: Props can be defined using an interface or type to enforce structure.

interface MyComponentProps {
  title: string;
}

const MyComponent: React.FC<MyComponentProps> = ({ title }) => {
  return <h1>{title}</h1>;
};
Enter fullscreen mode Exit fullscreen mode

Q80: How do you manage state in a TypeScript React application? πŸ“ˆ

A: State can be managed similarly to regular React, but types can be added to the state variables and the updater functions.

const [count, setCount] = useState<number>(0);
Enter fullscreen mode Exit fullscreen mode

17. Miscellaneous

Q81: What is the difference between a presentation component and a container component? 🎭

A:

  • Presentation Component: Focuses on UI and presentation logic, receiving data and callbacks via props.
  • Container Component: Manages state and logic, passing down data to presentation components.

Q82: What are fragment components in React? πŸ“¦

A: Fragments allow you to group multiple elements without adding an extra node to the DOM. They can be declared using <React.Fragment> or <>.

return (
  <>
    <h1>Hello</h1>
    <p>World</p>
  </>
);
Enter fullscreen mode Exit fullscreen mode

Q83: What is the purpose of the dangerouslySetInnerHTML attribute? ⚠️

A: dangerouslySetInnerHTML allows you to set HTML directly from React, but it should be used cautiously to avoid XSS vulnerabilities.

const htmlContent = { __html: '<h1>Hello</h1>' };
return <div dangerouslySetInnerHTML={htmlContent} />;
Enter fullscreen mode Exit fullscreen mode

Q84: How do you handle conditional rendering in React? πŸ”„

A: Conditional rendering can be achieved using JavaScript logical operators or ternary expressions to decide what to render based on certain conditions.

return isLoggedIn ? <Dashboard /> : <Login />;
Enter fullscreen mode Exit fullscreen mode

Q85: What are refs in React? πŸ“œ

A: Refs are used to directly access a DOM element or a class component instance. They can be created using React.createRef() or the useRef hook.

const myRef = useRef(null);

const focusInput = () => {
  myRef.current.focus();
};

return <input ref={myRef} />;
Enter fullscreen mode Exit fullscreen mode

18. Common Errors and Solutions

Q86: What is the error "Warning: Each child in a list should have a unique key prop"? ⚠️

A: This warning occurs when rendering a list of elements without providing a unique key prop for each child. It can be resolved by ensuring each item has a unique identifier.

Q87: How do you resolve "Maximum update depth exceeded" error? πŸ”„

A: This error occurs when there is an infinite loop of updates in the component. It can be resolved by checking the dependencies in hooks or preventing state updates that trigger re-renders.

Q88: What does "Uncaught TypeError: Cannot read property '...' of undefined" mean? πŸ“‰

A: This error indicates that you are trying to access a property of undefined, often due to improper state management or missing props. It can be resolved by ensuring the variable is defined before accessing its properties.

Q89: How do you fix "Cannot find module" error? πŸ“¦

A: This error occurs when a module is not found. It can be fixed by checking the import paths, ensuring the module is installed, or restarting the development server.

Q90: What does "Invalid prop" warning mean? ⚠️

A: This warning indicates that a component received a prop that doesn't match the expected type or format. It can be resolved by ensuring that the correct prop types are passed.

19. Testing

Q91: How do you test React components? πŸ§ͺ

A: React components can be tested using libraries like Jest and React Testing Library. You can write unit tests to verify the rendering and functionality of components.

import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('renders button', () => {
  render(<MyComponent />);
  const buttonElement = screen.getByText(/click me/i);
  expect(buttonElement).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

Q92: What is Jest? πŸ“š

A: Jest is a JavaScript testing framework that provides a rich API for writing tests. It includes features like test runners, assertion libraries, and mocking capabilities.

Q93: What is React Testing Library? πŸ“–

A: React Testing Library is a testing utility that focuses on testing the user interface from the user’s perspective. It encourages good testing practices and provides utilities for rendering components and querying the DOM.

Q94: How do you mock API calls in tests? 🎭

A: API calls can be mocked using libraries like msw (Mock Service Worker) or by using Jest's built-in mocking capabilities to simulate responses without making actual network requests.

Q95: What is snapshot testing? πŸ“Έ

A: Snapshot testing is a technique in which the rendered output of a component is saved to a file, and subsequent tests compare the output to ensure it hasn’t changed unexpectedly.

20. Performance Optimization

Q96: How do you optimize React performance? πŸš€

A: Performance can be optimized by:

  • Using React.memo: To prevent unnecessary re-renders of functional components.
  • Using shouldComponentUpdate: In class components to control re-renders.
  • Code splitting: To load only the required parts of the application.

Q97: What is lazy loading in React? ⏳

A: Lazy loading is a technique to load components only when they are needed. It can be achieved using React.lazy and Suspense.

const LazyComponent = React.lazy(() => import('./LazyComponent'));

return (
  <Suspense fallback={<div>Loading...</div>}>
    <LazyComponent />
  </Suspense>
);
Enter fullscreen mode Exit fullscreen mode

Q98: How do you profile a React application? πŸ“Š

A: You can profile a React application using the React Developer Tools, which provide insights into component render times and performance bottlenecks.

Q99: What is memoization? πŸ”

A: Memoization is an optimization technique that caches the results of expensive function calls and returns the cached result when the same inputs occur again.

Q100: How do you prevent memory leaks in React? 🧹

A: To prevent memory leaks:

  • Clean up subscriptions, timers, or event listeners in the useEffect cleanup function.
  • Avoid holding references to unmounted components.

Top comments (0)