React Questions and Answers
1. What is a lifecycle method of React?
In React, lifecycle methods are functions that allow components to run code at specific times in the
component's lifecycle: mounting, updating, and unmounting.
- Mounting: componentDidMount()
- Updating: componentDidUpdate()
- Unmounting: componentWillUnmount()
Functional components do not have lifecycle methods but use useEffect() for similar functionality.
---
2. How do you reduce the load time of a React application?
To reduce load time:
- Use code-splitting and lazy loading.
- Optimize images.
- Compress assets using Gzip or Brotli.
- Implement caching via service workers.
---
3. How to optimize the performance of a React app?
- Use React.memo() for component memoization.
- Use useMemo() and useCallback() to cache expensive calculations.
- Code-splitting using React.lazy().
- Avoid inline functions and objects.
- Optimize state management (e.g., using Redux).
- Implement list virtualization using libraries like react-window.
---
4. Is componentDidMount equivalent to useEffect()?
Yes, componentDidMount() in class components is similar to useEffect(() => {...}, []) in functional
components, as both are invoked after the component mounts. However, useEffect is more flexible
and can handle updates and unmounts as well.
---
5. Lifecycle of functional components
In functional components, lifecycle stages are handled using the useEffect() hook:
- Mounting: useEffect(() => {...}, [])
- Updating: useEffect(() => {...}, [dependencies])
- Unmounting: Return a cleanup function from useEffect() to simulate componentWillUnmount().