1. What is React?
React is a JavaScript library for building user interfaces, developed by Facebook. It allows developers to build single-page applications with a component-based architecture.
2. What are the key features of React?
The key features of React are:
- Component-based architecture
- Virtual DOM
- Unidirectional data flow
- Declarative syntax
- JSX (JavaScript XML)
3. What is JSX in React?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript. JSX is transpired into regular JavaScript using tools like Babel.
4. What is the Virtual DOM?
The Virtual DOM is a lightweight copy of the actual DOM in memory. React uses the Virtual DOM to improve performance by minimizing direct manipulation of the real DOM. React updates only the parts of the DOM that have changed.
5. What is the difference between a functional component and a class component?
A functional component is a JavaScript function that accepts props as an argument and returns React elements. A class component is a ES6 class that extends from `React.Component` and can have lifecycle methods and state.
6. What is state in React?
State is a JavaScript object that holds dynamic data in a React component. The state can be changed, which causes the component to re-render.
7. What is props in React?
Props (short for properties) are used to pass data from a parent component to a child component. Props are read-only and cannot be modified by the child component.
8. What are lifecycle methods in React?
Lifecycle methods are special methods that allow you to run code at different stages of a component's life. Common lifecycle methods include `componentDidMount`, `shouldComponentUpdate`, and `componentWillUnmount`.
9. What is the use of `componentDidMount` in React?
`componentDidMount` is a lifecycle method that is called once, immediately after a component is added to the DOM. It's commonly used to fetch data or perform other setup tasks.
10. How do you handle events in React?
In React, events are handled using camelCase syntax. Event handlers are passed as props and written as functions, for example:
onClick={this.handleClick}
where `handleClick` is a function.11. What is `useState` hook in React?
The `useState` hook is used to add state to functional components. It returns an array with two elements: the current state value and a function to update it.
12. What is `useEffect` hook in React?
The `useEffect` hook is used to perform side effects in functional components. It runs after render and can be used for tasks like fetching data, setting up subscriptions, and manually changing the DOM.
13. What is the difference between `useEffect` and `componentDidMount`?
`useEffect` serves the same purpose as `componentDidMount` in class components, but it can also handle other lifecycle events, such as when the component updates or unmounts.
14. What is the `useContext` hook in React?
The `useContext` hook allows you to access the value of a React context without the need for a consumer component. It is commonly used for sharing state across multiple components without having to prop-drill.
15. What is `React Router`?
React Router is a standard library for routing in React applications. It allows you to define routes in your application and navigate between different components based on the URL.
16. How do you pass data between components in React?
Data is passed between components in React using props. A parent component can pass data to a child component by including props in the child component's tag.
17. What are keys in React?
Keys are unique identifiers used to help React identify which items in a list are changed, added, or removed. Keys should be stable, unique, and consistent between renders.
18. What is the purpose of `shouldComponentUpdate`?
`shouldComponentUpdate` is a lifecycle method that allows you to optimize performance by determining whether a component should re-render when new props or state are received.
19. What are React fragments?
React Fragments allow you to group a list of children without adding extra nodes to the DOM. You can use the `Fragment` component or the shorthand `<>...>`.
20. How can you update state in React?
State can be updated using the `setState` method in class components or the state updater function from the `useState` hook in functional components.
21. What is React Context?
React Context is a way to share values like themes, authentication, or language preferences across multiple components without passing props manually through every level of the component tree.
22. What is Redux in React?
Redux is a state management library that helps manage the state of an application in a predictable way. It uses a single global store and actions to update the state, making state management easier to handle in complex applications.
23. What is a controlled component?
A controlled component is a component that takes its current value from React state and updates the value through `setState` or a state updater function.
24. What is an uncontrolled component?
An uncontrolled component is a component that manages its own state internally, typically using the DOM to handle form elements. You can access the value of an uncontrolled component using a `ref`.
25. What are React hooks?
React hooks are functions that allow you to use React features like state, lifecycle methods, and context in functional components. Common hooks include `useState`, `useEffect`, and `useContext`.
26. What is the `useRef` hook in React?
The `useRef` hook is used to persist values across renders without causing re-renders. It is commonly used for referencing DOM elements and keeping mutable values.
27. What is the `useMemo` hook in React?
The `useMemo` hook is used to memoize a calculation result so that it is recomputed only when the dependencies change, improving performance by preventing unnecessary re-calculations.
28. What is `useCallback` in React?
The `useCallback` hook is used to memoize functions so that they are not recreated on each render unless the dependencies change.
29. What is the `React.StrictMode`?
`React.StrictMode` is a development tool that helps identify potential problems in an application, such as unsafe lifecycle methods or deprecated APIs.
30. How do you handle forms in React?
Forms in React are typically handled using controlled components where the form element's value is stored in the component's state. On each change, the `setState` method is called to update the state.
31. What is the output of the following code?
function Test() { const [count, setCount] = useState(0); return ; }
The component renders a button that displays a count value. Each time the button is clicked, the count increases by 1.
32. What is a higher-order component (HOC)?
A higher-order component (HOC) is a function that takes a component and returns a new component with additional props or logic. HOCs are commonly used for cross-cutting concerns like authentication, routing, etc.
33. What is `React.createElement`?
`React.createElement` is a function used by React to create elements that can be rendered to the DOM. JSX is transpiled into `React.createElement` calls.
34. What is the purpose of `key` prop in React?
The `key` prop is used to uniquely identify elements in a list of elements. React uses it to efficiently update and re-render components.
35. What are React portals?
React portals allow you to render children components outside the parent component's DOM hierarchy, often used for modals, tooltips, and sidebars.
36. What is the purpose of the `dangerouslySetInnerHTML` attribute in React?
`dangerouslySetInnerHTML` is used to set HTML content directly into the DOM, which can be risky because it opens the door to cross-site scripting (XSS) vulnerabilities. It should be used carefully and only when absolutely necessary.
37. How can you optimize performance in React applications?
To optimize performance in React:
- Use `React.memo` for functional components to prevent unnecessary re-renders.
- Use `shouldComponentUpdate` in class components to avoid unnecessary re-renders.
- Implement code-splitting with `React.lazy` and `Suspense`.
- Use the `useMemo` and `useCallback` hooks to memoize values and functions.
38. What is `React.lazy` and `Suspense`?
`React.lazy` is used to dynamically import components when they are needed, while `Suspense` is used to handle the loading state of lazy-loaded components. Together, they help with code splitting and reduce the initial bundle size.
39. What is the use of `useLayoutEffect` hook in React?
`useLayoutEffect` is similar to `useEffect`, but it runs synchronously after all DOM mutations. It is used to measure DOM elements or trigger reflows before the browser paints the screen, ensuring a smooth experience.
40. Can you explain what `useImperativeHandle` does?
`useImperativeHandle` is a hook used to customize the instance value that is exposed to parent components when using `ref`. This is useful when you want to expose specific methods or properties from a child component.
41. What is `React.StrictMode` and when should you use it?
`React.StrictMode` is a development-only feature that helps identify potential problems in the application, such as deprecated APIs or unsafe lifecycle methods. It should be used during development but not in production.
42. What is the role of `useEffect` in React?
`useEffect` allows you to perform side effects in functional components, such as fetching data, subscribing to a service, or manually modifying the DOM after render. It replaces lifecycle methods like `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`.
43. How do you prevent a re-render of a component in React?
You can prevent a re-render by:
- Using `React.memo` for functional components.
- Using `shouldComponentUpdate` in class components to conditionally allow re-renders.
- Using the `useMemo` or `useCallback` hooks to memoize values and functions.
44. What is `useState` used for?
`useState` is a hook in React that allows you to add state to functional components. It returns an array with two elements: the current state value and a function to update it.
45. What are React refs and how do you use them?
Refs are used to directly access a DOM element or a component instance. You can create a ref using `React.createRef()` or the `useRef` hook, and then access the referenced element using `ref.current`.
46. What is the difference between `useState` and `useReducer`?
`useState` is a simpler hook used for managing state in functional components, while `useReducer` is more powerful and useful for complex state logic where the state depends on the previous state. `useReducer` is generally preferred when there are multiple state variables or complex state transitions.
47. How do you make API calls in React?
API calls can be made in React using JavaScript's `fetch` API or Axios. Commonly, you would place API calls inside the `useEffect` hook to fetch data when the component mounts.
Example:
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
48. What are controlled components in React?
Controlled components are form elements that are controlled by React state. The input value is set using state and is updated using `setState` or the state updater function from the `useState` hook.
49. What are uncontrolled components in React?
Uncontrolled components are form elements where React does not manage the state. Instead, you interact with the DOM directly using `ref` to access values.
50. What are higher-order components (HOCs) in React?
Higher-order components (HOCs) are functions that take a component and return a new component with additional props or logic. HOCs are commonly used for reusing component logic, such as authentication or routing.
51. How does React handle two-way data binding?
In React, two-way data binding is handled using controlled components. The form element value is controlled by React state, and any changes to the form element are handled through event handlers that update the state.
52. How would you implement a custom hook in React?
A custom hook is simply a function that uses React hooks like `useState`, `useEffect`, or `useRef`. It allows you to encapsulate and reuse logic across different components. Example:
function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(error); return initialValue; } }); const setValue = value => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.error(error); } }; return [storedValue, setValue]; }
53. What is Prop drilling?
Prop drilling refers to passing props from a parent component down to deeply nested child components. This can be inefficient and hard to maintain, especially in large applications. React Context can be used as an alternative to prop drilling.
54. What is the use of `React.Fragment`?
`React.Fragment` is used to group multiple elements without adding an extra DOM node. It helps to avoid unnecessary wrapper elements in the rendered HTML.
55. How do you handle error boundaries in React?
Error boundaries are components that catch JavaScript errors in their child components, log the error, and display a fallback UI. You can create error boundaries by implementing the `componentDidCatch` lifecycle method in class components or using the `static getDerivedStateFromError` method.
56. What is a render prop?
A render prop is a function that returns a React element. It allows for the sharing of code between components by passing a function as a prop, which is then called to render content.
57. What is the purpose of the `key` prop in a list?
The `key` prop is used to uniquely identify each element in a list. React uses the `key` prop to optimize rendering by only updating the parts of the list that have changed, instead of re-rendering the entire list.
58. What is `React.memo`?
`React.memo` is a higher-order component used to memoize functional components. It prevents unnecessary re-renders of a component if its props haven't changed.
59. How do you handle routing in React?
Routing in React is typically handled using the `react-router-dom` library. You can define routes using `Route` components and navigate between them using `Link` or `useHistory` hooks.
60. How do you pass children to a component in React?
You can pass children to a React component by including them between the opening and closing tags of the component, like this:
Children content goes here
Inside the component, children can be accessed via `props.children`.61. What are the advantages of using JSX in React?
JSX provides a more readable and declarative way to write UI components. It allows HTML-like syntax in JavaScript, enabling easier manipulation and rendering of UI elements. Additionally, JSX makes the code more predictable and helps developers better visualize the UI structure.
62. What is the purpose of `useContext` hook in React?
The `useContext` hook allows you to access the value of a context directly without needing to use `Context.Consumer`. It simplifies the process of consuming context values inside functional components.
63. What is React Context API?
The React Context API is a way to share values like themes, authentication, or settings globally across components without having to pass props manually at every level. It provides a more efficient way to manage global state in a React app.
64. What is the purpose of `useReducer` hook?
`useReducer` is used to manage state that is more complex than what `useState` can handle. It is particularly useful when the next state depends on the previous one or when the state logic involves multiple sub-values. It works like a Redux reducer but at the component level.
65. What is the difference between `useEffect` and `componentDidMount`?
`useEffect` is a hook that runs side effects in functional components. It can be configured to run on component mount, update, or unmount. `componentDidMount` is a class lifecycle method that runs only once after the component mounts. `useEffect` can handle a wider range of effects with more flexibility.
66. How do you optimize the rendering of large lists in React?
To optimize the rendering of large lists in React, you can use techniques such as:
- Lazy loading data to render items as they come into view (e.g., using `react-window` or `react-virtualized`).
- Using `key` prop to avoid unnecessary re-renders.
- Implementing `React.memo` for components that do not need to re-render.
- Using the `useMemo` hook to memoize computed data.
67. What is the `dangerouslySetInnerHTML` prop used for?
The `dangerouslySetInnerHTML` prop allows you to set HTML content inside a component. However, it should be used carefully as it bypasses React's built-in protection against XSS (cross-site scripting) attacks. It is typically used for rendering content from trusted sources, like rich text.
68. What is `forwardRef` in React?
`forwardRef` is a higher-order component used to pass a ref from a parent component to a child component. It allows the parent to directly interact with a child component's DOM or instance.
69. What are render props in React?
Render props are a pattern in React where a function is passed as a prop to a component. This function returns a React element that can be dynamically rendered, enabling code reuse across components.
70. What is the purpose of `React.PureComponent`?
`React.PureComponent` is a base class for components that only re-render when the props or state have changed. It implements `shouldComponentUpdate` with a shallow prop and state comparison, which can improve performance by preventing unnecessary renders.
71. How do you share state between sibling components in React?
You can share state between sibling components in React by lifting the state up to the closest common ancestor. The parent component can pass the state as props to the sibling components.
72. What is the `useCallback` hook used for in React?
The `useCallback` hook is used to memoize functions, ensuring that the function reference stays the same between renders unless its dependencies change. This is useful to prevent unnecessary re-renders of components that depend on the function.
73. How can you handle forms in React?
Forms in React can be handled using controlled components (where the form elements' values are managed by React state) or uncontrolled components (where the DOM itself handles the form state via `refs`). Controlled components provide a more consistent way to manage form data.
74. What is the significance of `componentDidUpdate` in React?
`componentDidUpdate` is a lifecycle method in class components that is called after a component’s state or props have been updated. It allows you to perform side effects in response to prop or state changes.
75. What is the difference between `React.createElement` and JSX?
`React.createElement` is the function that React uses under the hood to create elements from JSX. JSX is a syntax extension that looks like HTML, but it is transformed into `React.createElement` calls during compilation. JSX is more readable and convenient, while `React.createElement` is the raw way of defining React elements.
76. How would you make a component lazy-loadable in React?
You can make a component lazy-loadable in React by using the `React.lazy` function. This function dynamically imports the component, allowing it to be loaded only when needed. You would typically pair `React.lazy` with the `Suspense` component to handle loading states.
77. What are Hooks in React?
Hooks are functions that allow you to use state and other React features in functional components. Common hooks include `useState`, `useEffect`, `useContext`, `useReducer`, `useRef`, and `useMemo`.
78. What is the `useEffect` cleanup function used for?
The `useEffect` cleanup function is used to clean up side effects when the component unmounts or when certain dependencies change. For example, you can clear timers, unsubscribe from services, or reset resources.
79. What is React Router and how does it work?
React Router is a library used to handle routing in React applications. It allows you to define routes in your application and navigate between them. It uses components like `Route`, `Link`, `Switch`, and `BrowserRouter` to handle navigation.
80. How do you pass data from parent to child components in React?
In React, you pass data from parent to child components through props. The parent component provides the data, and the child component accesses it via the `props` object.
81. What is `useEffect` dependency array in React?
The dependency array of `useEffect` specifies when the effect should run. If the array is empty (`[]`), the effect runs only once after the initial render. If there are dependencies, the effect runs whenever any of the dependencies change.
82. How would you share state across different pages in a React app?
You can share state across different pages by using the React Context API, Redux, or other state management libraries. React Router can also be used in conjunction with these solutions to manage state between different pages.
83. What are some common performance optimizations for React?
Some common performance optimizations for React include:
- Using `React.memo` to memoize functional components.
- Using `useMemo` and `useCallback` hooks to memoize values and functions.
- Lazy loading components with `React.lazy`.
- Virtualizing large lists using libraries like `react-window`.
84. What is the `useRef` hook in React?
The `useRef` hook allows you to persist values across renders without causing a re-render. It is commonly used to access DOM elements or store mutable values that do not trigger re-renders when updated.
85. What is the purpose of `React.StrictMode`?
`React.StrictMode` is a development tool that helps identify potential problems in an application. It checks for deprecated APIs, unsafe lifecycle methods, and other issues during development without affecting the production build.
86. How do you handle error boundaries in React?
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. You can implement an error boundary by creating a class component that implements `componentDidCatch` or `static getDerivedStateFromError` lifecycle methods.
87. What is the `useLayoutEffect` hook in React?
The `useLayoutEffect` hook is similar to `useEffect`, but it runs synchronously after all DOM mutations. It is used to read and make changes to the DOM before the browser paints, allowing you to measure the layout and adjust before the screen updates.
88. What is the difference between `useEffect` and `useLayoutEffect`?
`useEffect` runs asynchronously after the paint, while `useLayoutEffect` runs synchronously before the paint. `useLayoutEffect` is used for cases where you need to measure DOM or make layout changes before the user sees the updates, while `useEffect` is used for other side effects like fetching data.
89. What is the purpose of `useImperativeHandle` in React?
`useImperativeHandle` is a hook that customizes the instance value that is exposed when using `React.forwardRef`. It allows you to modify the ref object, making it possible to expose specific methods to the parent component.
90. How does `React.memo` optimize functional components?
`React.memo` is a higher-order component that prevents unnecessary re-renders of functional components by performing a shallow comparison of props. If the props haven’t changed, it skips the render process and returns the previous output, improving performance.
91. What is `React.Fragment` and why would you use it?
`React.Fragment` is a component that allows you to return multiple elements without adding extra nodes to the DOM. It is useful when you need to group elements for rendering purposes without introducing unnecessary wrapper elements.
92. How do you handle prop types in React?
Prop types can be validated using the `prop-types` library in React. This library allows you to define the expected data types for props, providing runtime checks for type validation and improving the code quality.
93. What is the `useState` hook and how do you use it?
`useState` is a hook that allows you to add state to functional components. You call `useState(initialValue)` to declare a state variable. The hook returns an array with the current state value and a function to update that value.
94. What is the difference between `useState` and `useReducer`?
`useState` is best for managing simple states, while `useReducer` is more suitable for complex state logic or when the next state depends on the previous one. `useReducer` is inspired by Redux and allows you to handle state transitions through actions.
95. What is React’s reconciliation process?
Reconciliation is the process React uses to update the DOM by comparing the new virtual DOM with the previous one and applying the necessary updates efficiently. React uses an algorithm called the "diffing algorithm" to find the minimal set of changes.
96. What is the purpose of `key` prop in React lists?
The `key` prop is used to uniquely identify elements in a list, enabling React to efficiently update and re-render the correct items when the list changes. This helps React to track changes, additions, or deletions in the list and optimize rendering.
97. What is the difference between `Class components` and `Functional components` in React?
Class components are ES6 classes that extend `React.Component` and have access to lifecycle methods. Functional components are simpler and do not have lifecycle methods, but with the introduction of hooks, functional components can now manage state and side effects.
98. How can you handle authentication in React?
Authentication in React is usually handled using a combination of React Router for routing and context or Redux for managing user state. You can store the authentication token in localStorage or sessionStorage and protect routes using a private route component.
99. What is the `useEffect` hook's cleanup function and when should it be used?
The cleanup function inside `useEffect` is used to clean up resources like event listeners, timers, subscriptions, etc., before the component is removed or before the effect runs again. It’s important to prevent memory leaks and unwanted side effects.
100. What are higher-order components (HOCs) in React?
Higher-order components (HOCs) are functions that take a component and return a new component with additional props or behavior. HOCs are used for code reuse, logic abstraction, and enhancing components with additional functionality, like authentication or logging.