{"id":24813712,"url":"https://github.com/rabi-siddique/react-js-interview-questions","last_synced_at":"2026-05-01T12:33:11.211Z","repository":{"id":216608229,"uuid":"741577942","full_name":"rabi-siddique/react-js-interview-questions","owner":"rabi-siddique","description":"A list of React Interview Questions that I personally I feel are enough to cover for all types of React based interviews. ","archived":false,"fork":false,"pushed_at":"2024-01-23T17:19:15.000Z","size":24,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-05T23:47:27.544Z","etag":null,"topics":["coding","frontend","programming","react","react-native","reactjs","webdevelopment"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rabi-siddique.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-01-10T17:24:23.000Z","updated_at":"2024-01-31T17:32:05.000Z","dependencies_parsed_at":"2024-01-16T12:37:32.152Z","dependency_job_id":"96c99634-6521-4b08-a618-59a80ec62f5e","html_url":"https://github.com/rabi-siddique/react-js-interview-questions","commit_stats":null,"previous_names":["rabi-siddique/react-js-interview-questions"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/rabi-siddique/react-js-interview-questions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Freact-js-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Freact-js-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Freact-js-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Freact-js-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rabi-siddique","download_url":"https://codeload.github.com/rabi-siddique/react-js-interview-questions/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Freact-js-interview-questions/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32497812,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-30T13:12:12.517Z","status":"online","status_checked_at":"2026-05-01T02:00:05.856Z","response_time":64,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["coding","frontend","programming","react","react-native","reactjs","webdevelopment"],"created_at":"2025-01-30T15:51:49.641Z","updated_at":"2026-05-01T12:33:11.191Z","avatar_url":"https://github.com/rabi-siddique.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# What is the Virtual DOM?\n\nThe Virtual DOM (Document Object Model) is a concept used in web development frameworks, particularly popularized by React. It is a lightweight copy of the actual DOM, a representation of the structure of a web page. When changes are made to the data in a web application, the Virtual DOM is updated first rather than directly manipulating the real DOM.\n\nA simplified process of how the Virtual DOM works:\n\n**Initial Render**: The Virtual DOM is created based on the initial state of the application.\n\n**Updates**: When the state of the application changes, a new Virtual DOM is created.\n\n**Diffing**: The new Virtual DOM is compared with the previous one to identify the differences or changes (diffing).\n\n**Reconciliation**: Only the differences are then applied to the actual DOM, minimizing the amount of manipulation needed and improving performance.\n\nThe Virtual DOM helps optimize the rendering process by reducing the number of direct manipulations on the real DOM, which is a more expensive operation.\n\n# What does `create-react-app` do?\n\nIt is a command line tool that helps create a boilerplate react project with the pre-configured development environment.\n\nThis includes the build setup using module bundlers like Webpack and a development server for testing the application locally.\n\nIt also sets up a testing environment using Jest and provides the necessary configurations for writing and executing tests for your React components.\n\nThis helps developers to get started quickly in building their applications instead of spending time on configuring setups for the build.\n\n# What's the purpose of binding in class components?\n\nThe binding step is necessary because class methods don’t automatically bind this to the class instance. Let’s demonstrate it with the help of the following ES6 class component:\n\n```js\nclass ExplainBindingsComponent extends Component {\n  onClickMe() {\n    console.log(this);\n  }\n\n  render() {\n    return (\n      \u003cbutton onClick={this.onClickMe} type='button'\u003e\n        Click Me\n      \u003c/button\u003e\n    );\n  }\n}\n```\n\nThe component renders just fine, but when you click the button, you see undefined in your developer console log. This is one of the main sources of bugs developers encounter in React. If you want to access this.state in your class method, it cannot be retrieved because this is undefined. To make this accessible in your class methods, you have to bind the class methods to this. In the following class component the class method is properly bound in the class constructor:\n\n```js\nclass ExplainBindingsComponent extends Component {\n  constructor() {\n    super();\n\n    this.onClickMe = this.onClickMe.bind(this);\n  }\n\n  onClickMe() {\n    console.log(this);\n  }\n\n  render() {\n    return (\n      \u003cbutton onClick={this.onClickMe} type='button'\u003e\n        Click Me\n      \u003c/button\u003e\n    );\n  }\n}\n```\n\nSome things to avoid would be to stop binding in the render method. Because in that case, binding happens every time the render() method runs, meaning every time the component updates, which will hurt your application’s performance eventually. Binding the class method in the constructor need only be done once, when the component is instantiated.\n\nSome developers will define the business logic of their class methods in the constructor. Avoid this approach as well, as it will clutter your constructor over time. The constructor is only there to instantiate your class with all its properties, so the business logic of class methods should be defined outside the constructor.\n\nClass methods can be auto-bound using JavaScript ES6 arrow functions:\n\n```js\nclass ExplainBindingsComponent extends Component {\n  onClickMe = () =\u003e {\n    console.log(this);\n  };\n\n  render() {\n    return (\n      \u003cbutton onClick={this.onClickMe} type='button'\u003e\n        Click Me\n      \u003c/button\u003e\n    );\n  }\n}\n```\n\nUse this method if the repetitive binding in the constructor annoys you.\n\n# What's the difference between Controlled and UnControlled Components?\n\nControlled components get their data from a parent, using props. The state is typically handled by the parent component, and any changes to the state are passed down to the child component via props. On the other hand, Uncontrolled components do their own thing. They take care of their own data/state without relying on a parent to manage it.\n\nSince the parent manages their state, controlled components are more predictable. Data flow is controlled and consistent, making it simpler to debug and trace issues. As changes in the component's state are initiated and directed by the parent. A downside with Controlled components would be that it involve more code to handle the flow of data between parent and child components.\n\n# What are Functional Stateless Components?\n\nThese components are stateless, meaning they don't manage local state within the component. They solely rely on the input provided through props to determine their behavior and render content. Functional Stateless Components are functions that take input and return an output. The inputs are the props, and the output is a component instance in plain JSX. They have no local state (stateless). You cannot access or update the state.\n\n# When does constructor method and render method runs in the context of class methods?\n\nThe constructor runs only once in the lifetime of a component, whereas the render() class method runs once at the beginning and every time the component updates.\n\n# What's the difference between Named \u0026 Default Exports?\n\nIn JavaScript ES6, you can import and export functionalities from modules. These can be functions, classes, components, constants, essentially anything you can assign to a variable. The act of exporting one or multiple variables is called a named export:\n\n```js\n// file1\nconst firstname = 'Rabi';\nconst lastname = 'Siddique';\n\nexport { firstname, lastname };\n```\n\nAnd import them in another file with a relative path to the first file.\n\n```js\n// file2.js\nimport { firstname, lastname } from './file1.js';\n```\n\nOn the other hand, default statement can be used to export and import a single functionality.\n\n```js\n// file1.js\nconst person = {\n  firstname: 'Rabi',\n  lastname: 'Siddique',\n};\n\nexport default person;\n```\n\nYou have to leave out the curly braces to import the default export. Also the import name can differ from the exported default name.\n\n```js\nimport rabi from './file1.js';\n```\n\n# What is One-Way Data Flow in React and How it useful?\n\nReact follows one way data flow. That means I can pass data from parent component to the child components. But, I cannot pass data from child components to parent components.\n\nIf I have an issue in the parent component. I know that it's because of the parent component and not the child component. Because, the child components cannot mess with it's parent component. Basically, it makes debugging in React straight-forward.\n\n# What is TreeShaking?\n\nTree shaking is the optimization process that selectively includes only the essential, or live code in a final bundle. This technique ensures that the generated bundle contains only the code that is actively utilized in your project.\n\nFor example, I make the import:\n\n```js\nimport ReactDOM from 'react-dom';\n```\n\nIn this initial import, the entire react-dom library is included. However, with tree shaking, you can optimize further by importing only the specific component you require:\n\n```js\nimport { createRoot } from 'react-dom';\n```\n\nThis is better because when the final bundle is created, only the implemenation of createRoot is includeded. And not the entire ReactDOM.\n\n# Why Hooks should be called at the top level of your React function?\n\nIn React, Hooks should be called at the top of your functional component. We should not place them inside conditionals, loops or nested functions. But why? This is because React keeps track of the order by which these hooks are called. Using this order, React is able to maintain state values between re-renders. If you mix up the order of these steps, React gets confused, and it can't keep the data in order.\n\nFor example, consider this component:\n\n```js\nfunction Form() {\n  // 1. Use the name state variable\n  const [name, setName] = useState('Mary');\n\n  // 2. Use an effect for persisting the form\n  useEffect(function persistForm() {\n    localStorage.setItem('formData', name);\n  });\n\n  // 3. Use the surname state variable\n  const [surname, setSurname] = useState('Poppins');\n\n  // 4. Use an effect for updating the title\n  useEffect(function updateTitle() {\n    document.title = name + ' ' + surname;\n  });\n\n  // ...\n}\n```\n\nHow does React know which state corresponds to which useState call? The answer is that React relies on the order in which Hooks are called. Above example works because the order of the Hook calls is the same on every render:\n\n```js\n// ------------\n// First render\n// ------------\nuseState('Mary'); // 1. Initialize the name state variable with 'Mary'\nuseEffect(persistForm); // 2. Add an effect for persisting the form\nuseState('Poppins'); // 3. Initialize the surname state variable with 'Poppins'\nuseEffect(updateTitle); // 4. Add an effect for updating the title\n\n// -------------\n// Second render\n// -------------\nuseState('Mary'); // 1. Read the name state variable (argument is ignored)\nuseEffect(persistForm); // 2. Replace the effect for persisting the form\nuseState('Poppins'); // 3. Read the surname state variable (argument is ignored)\nuseEffect(updateTitle); // 4. Replace the effect for updating the title\n\n// ...\n```\n\nAs long as the order of the Hook calls is the same between renders, React can associate some local state with each of them. But what happens if we put a Hook call inside a condition?\n\n```js\n// 🔴 We're breaking the first rule by using a Hook in a condition\nif (name !== '') {\n  useEffect(function persistForm() {\n    localStorage.setItem('formData', name);\n  });\n}\n```\n\nThe name !== '' condition is true on the first render, so we run this Hook. However, on the next render the user might clear the form, making the condition false. Now that we skip this Hook during rendering, the order of the Hook calls becomes different:\n\n```js\nuseState('Mary'); // 1. Read the name state variable (argument is ignored)\n// useEffect(persistForm)  // 🔴 This Hook was skipped!\nuseState('Poppins'); // 🔴 2 (but was 3). Fail to read the surname state variable\nuseEffect(updateTitle); // 🔴 3 (but was 4). Fail to replace the effect\n```\n\nReact wouldn’t know what to return for the second useState Hook call. React expected that the second Hook call in this component corresponds to the persistForm effect, just like during the previous render, but it doesn’t anymore. From that point, every next Hook call after the one we skipped would also shift by one, leading to bugs.\n\n# Why Local Variables are not suitable for states?\n\nThere are two reasons why local reasons are not perfect to be used as states.\n\n1. Betweeen re-renders the values of local variables are not preserved. It is set to its original value. This is because when React renders a component, it renders it from scratch.\n2. Local variables dont trigger renders. Due to which we can't reflect the values of local variables on the screen in case they change.\n\n# How does React handle multiple consecutive calls to the set function of the state in the same render cycle?\n\nWithin a render, the value of state remains the same. Also, when setting the state using `set` function, it changes it for the next render only. For example, consider this snippet:\n\n```js\nimport { useState } from 'react';\n\nexport default function Counter() {\n  const [number, setNumber] = useState(0);\n\n  return (\n    \u003c\u003e\n      \u003ch1\u003e{number}\u003c/h1\u003e\n      \u003cbutton\n        onClick={() =\u003e {\n          setNumber(number + 1);\n          setNumber(number + 1);\n          setNumber(number + 1);\n        }}\u003e\n        +3\n      \u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\nIn this snippet, upon clicking the button, you might think the state is being updated 3 times, so in the next render, the value might be 3. Which is not the case. React updates states only for the next render.\nWhich means no matter how many times you call `set` function, it will update state based on the current value for the very next render. Which in this will be 1.\n\n# What are Refs in React?\n\nRefs are useful when we want a component to remember information without triggering renders on value changes. You can use refs by importing the `useRef` hook and pass it an initial value:\n\n```js\nimport { useRef } from 'react';\nconst ref = useRef(0);\n\n// Returns a plain object:\n\n/*\n\n{ \n  current: 0 // The value you passed to useRef\n}\n\n*/\n```\n\nWe can access the current value of the ref using `ref.current` property. This value is intentionally mutable, meaning you can both read and write to it.\n\n# How Refs are different from State?\n\n- `useRef(initialValue)` returns `{ current: initialValue }`. While `useState(initialValue)` returns the current value of a state variable and a state setter function `( [value, setValue])`.\n\n- Refs doesn’t trigger re-render when you change it, unlike states.\n\n- Refs are mutable while state is immutable.\n\n- Refs are synchronous. State acts like a snapshot for every render and doesn’t update synchronously. But when you mutate the current value of a ref, it changes immediately:\n\n```js\nref.current = 5;\nconsole.log(ref.current); // 5\n```\n\n# When should we use Refs?\n\nRefs are handy when you want to step outside of React and perhaps want to access to some external browser APIs. Some situations we can use refs:\n\n- Storing timeout IDs.\n- Manipulating and accessing DOM elements directly.\n\nAlthough, React automaitcally updates the DOM as a result we don't need to do it ourselves. However, there are times when we need access to a DOM element, for example to focus an input field, or getting the size of an element or scroll an element. React does not have any inbuilt method to do it. For this purpose, we can use of refs. Here is an example:\n\n```js\nimport { useRef } from 'react';\nconst myRef = useRef(null);\n\u003cdiv ref={myRef}\u003e\n```\n\nOn the initial render, `myRef` contains `null` until when React creates the DOM and points `myRef.current` to the `div` containing it. We can now access this DOM node from our event handlers and use the built-in browser APIs defined on it.\n\n# What are Forward Refs in React?\n\nYou cannot attach refs to our own defined components. By default, React returns `null` in this case. And it is intentional behavior. You will in fact get this warning:\n\n```bash\nWarning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?\n```\n\nThis is because by default, React does not allow component to access DOM nodes of another component, even if its a child component. Manually manipulating another component’s DOM nodes makes your code even more fragile.\n\nTo make sure, a component provides access to its DOM nodes, we have to make use of `forwardRef`. A component can specify that it `forwards` its ref to one of its children. For example:\n\n```js\nconst MyInput = forwardRef((props, ref) =\u003e {\n  return \u003cinput {...props} ref={ref} /\u003e;\n});\n```\n\n# How many steps are involved in any React Screen Update?\n\nAny screen update in a React app happens in three steps:\n\n1. Trigger\n2. Render\n3. Commit\n\n# How to Trigger a render in React?\n\nA render is trigger in React only two times. These are:\n\n1. Initial render of the component. It’s done by calling `createRoot` with the target DOM node, and then calling its render method with your component. Here is the code:\n\n```js\nimport Image from './Image.js';\nimport { createRoot } from 'react-dom/client';\n\nconst root = createRoot(document.getElementById('root'));\nroot.render(\u003cImage /\u003e);\n```\n\nIf we comment out this portion of the code, we will see a blank screen.\n\n2. A component's state is updated. When a component has been rendered initially we can trigger renders by updating state of the component using `set` function.\n\n# What is Rendering in React?\n\nRendering in React involves invoking functions. On the initial render its invoking the function of the root component. Subsequent renders invole invoking the function of the component whose state has been updated, along with any nested components.\n\nDuring this rendering process, React assesses the properties of these components to identify changes. The goal is to determine the most efficient way to apply these changes to the actual DOM. However, this information is not immediately utilized; it is held until the commit phase.\n\n# What is the Commit Phase in React?\n\nAfter rendering our components, React will modify the DOM now.\n\n1. For the initial render, React will use the appendChild() DOM API to put all the DOM nodes it has created on screen.\n2. For re-renders, React will apply the minimal necessary operations (calculated while rendering!) to make the DOM match the latest rendering output.\n\nReact only changes the DOM nodes if there’s a difference between renders. For example, Consider this component:\n\n```js\nexport default function Clock({ time }) {\n  return (\n    \u003c\u003e\n      \u003ch1\u003e{time}\u003c/h1\u003e\n      \u003cinput /\u003e\n    \u003c/\u003e\n  );\n}\n```\n\nIt re-renders with different props passed from its parent every second. Notice how you can add some text into the `\u003cinput\u003e`, updating its value, but the text doesn’t disappear when the component re-renders. This works because during this last step, React only updates the content of `\u003ch1\u003e` with the new time. It sees that the `\u003cinput\u003e` appears in the JSX in the same place as last time, so React doesn’t touch the `\u003cinput\u003e` or its value.\n\n# What is Painting in React?\n\nAfter rendering is done and React updated the DOM, the browser will repaint the screen. This process is known as `browser rendering`.\n\n# What are Effects in React?\n\nEffects let you run some code after rendering so that you can synchronize your component with some system outside of React Effects run at the end of a commit after the screen updates. An example of an effect is connecting to Chat server after the app loads, in case of a chat app. Which can done using the `useEffect` hock:\n\n```js\nimport { useEffect } from 'react';\n\nfunction MyComponent() {\n  useEffect(() =\u003e {\n    // Code here will run after *every* render\n  });\n  return \u003cdiv /\u003e;\n}\n```\n\nEvery time your component renders, React will update the screen and then run the code inside useEffect. **In other words, useEffect “delays” a piece of code from running until that render is reflected on the screen.**\n\nSummary of declaration of `useEffect`:\n\n```js\nuseEffect(() =\u003e {\n  // This runs after every render\n});\n\nuseEffect(() =\u003e {\n  // This runs only on mount (when the component appears)\n}, []);\n\nuseEffect(() =\u003e {\n  // This runs on mount *and also* if either a or b have changed since the last render\n}, [a, b]);\n```\n\n# What are cleanup functions in useEffect?\n\nSome Effects need to specify how to stop, undo, or clean up whatever they were doing. For example, `connect` needs `disconnect`, `subscribe` needs `unsubscribe`, and `fetch` needs either `cancel` or `ignore`. You do this by returning a cleanup function.\n\nYou’re writing a ChatRoom component that needs to connect to the chat server when it appears. You are given a `createConnection()` API that returns an object with `connect()` and `disconnect()` methods. Something like:\n\n```js\nfunction createConnection() {\n  // A real implementation would actually connect to the server\n  return {\n    connect() {\n      console.log('✅ Connecting...');\n    },\n    disconnect() {\n      console.log('❌ Disconnected.');\n    },\n  };\n}\n\nuseEffect(() =\u003e {\n  const connection = createConnection();\n  connection.connect();\n}, []);\n```\n\nImagine the `ChatRoom` component is a part of a larger app with many different screens. The user starts their journey on the `ChatRoom` page. The component mounts and calls `connection.connect()`. Then imagine the user navigates to another screen—for example, to the `Settings` page. The `ChatRoom` component unmounts. Finally, the user clicks `Back` and `ChatRoom` mounts again. This would set up a second connection—but the first connection was never destroyed! As the user navigates across the app, the connections would keep piling up.\n\nTo fix the issue, return a cleanup function from your Effect:\n\n```js\nuseEffect(() =\u003e {\n  const connection = createConnection();\n  connection.connect();\n  return () =\u003e {\n    connection.disconnect();\n  };\n}, []);\n```\n\nReact will call your cleanup function each time before the Effect runs again, and one final time when the component unmounts (gets removed). Let’s see what happens when the cleanup function is implemented:\n\n# Why does useEffect prints `✅ Connecting...` twice in code example below?\n\nCode Example:\n\n```js\nfunction createConnection() {\n  // A real implementation would actually connect to the server\n  return {\n    connect() {\n      console.log('✅ Connecting...');\n    },\n    disconnect() {\n      console.log('❌ Disconnected.');\n    },\n  };\n}\n\nuseEffect(() =\u003e {\n  const connection = createConnection();\n  connection.connect();\n}, []);\n```\n\nThis Effect only runs on **mount**, so you might expect `✅ Connecting...` to be printed once in the console. However, if you check the console, `✅ Connecting...` gets printed twice. Why does it happen?\n\nSeeing the `✅ Connecting...` log twice helps you notice the real issue: your code doesn’t close the connection when the component unmounts. Bugs like this are easy to miss without extensive manual testing. To help you spot them quickly, in development React remounts every component once immediately after its initial mount.\n\nTo fix the issue, return a cleanup function from your Effect:\n\n```js\nuseEffect(() =\u003e {\n  const connection = createConnection();\n  connection.connect();\n  return () =\u003e {\n    connection.disconnect();\n  };\n}, []);\n```\n\nLet’s see what happens when the cleanup function is implemented. Now you get three console logs in development:\n\n1. `✅ Connecting...`\n2. `❌ Disconnected.`\n3. `✅ Connecting...`\n\nThis is the correct behavior in development. By remounting your component, React verifies that navigating away and back would not break your code. Disconnecting and then connecting again is exactly what should happen! When you implement the cleanup well, there should be no user-visible difference between running the Effect once vs running it, cleaning it up, and running it again. There’s an extra connect/disconnect call pair because React is probing your code for bugs in development.\n\nIn production, you would only see `✅ Connecting...` printed once. Remounting components only happens in development to help you find Effects that need cleanup. You can turn off Strict Mode to opt out of the development behavior.\n\n# How to stop Event Propagation in React?\n\nBy default, events bubbles up or propagates in React. It starts with where the event happened, and then goes up the tree.\n\n```js\nexport default function Toolbar() {\n  return (\n    \u003cdiv\n      className='Toolbar'\n      onClick={() =\u003e {\n        alert('You clicked on the toolbar!');\n      }}\u003e\n      \u003cbutton onClick={() =\u003e alert('Playing!')}\u003ePlay Movie\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e alert('Uploading!')}\u003eUpload Image\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\nIn the example above, no matter which button we click, two callbacks will be called. One for the button we clicked and one for the `div`. To stop this, we use the `event` object received by event handlers. By convention, it’s usually called `e`, which stands for `event`. You can use this object to read information about the event. That event object also lets you stop the propagation. If you want to prevent an event from reaching parent components, you need to call `e.stopPropagation()` like this: Button component does:\n\n```js\nexport default function Toolbar() {\n  return (\n    \u003cdiv\n      className='Toolbar'\n      onClick={(e) =\u003e {\n        e.stopPropagation();\n        alert('You clicked on the toolbar!');\n      }}\u003e\n      \u003cbutton onClick={() =\u003e alert('Playing!')}\u003ePlay Movie\u003c/button\u003e\n      \u003cbutton\n        onClick={(e) =\u003e {\n          e.stopPropagation();\n          alert('Uploading!');\n        }}\u003e\n        Upload Image\n      \u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n# How to prevent Page Reloads on Form Submission in React?\n\nSome browser events have default behavior associated with them. For example, a `\u003cform\u003e` submit event, which happens when a button inside of it is clicked, will reload the whole page by default. You can call `e.preventDefault()` on the event object to stop this from happening:\n\n```js\nexport default function Signup() {\n  return (\n    \u003cform\n      onSubmit={(e) =\u003e {\n        e.preventDefault();\n        alert('Submitting!');\n      }}\u003e\n      \u003cinput /\u003e\n      \u003cbutton\u003eSend\u003c/button\u003e\n    \u003c/form\u003e\n  );\n}\n```\n\n# What is the difference between Functional and Class Based Components in React?\n\n1. Functional components utilize functions, whereas class-based components make use of ES6 classes.\n2. Since the advent of Hooks, functional components can use state through the `useState` hook. Conversely, class components manage local state using `this.state`.\n3. Class components have access to various lifecycle methods, such as `componentDidMount` and `componentDidUpdate`, which can be beneficial for specific tasks. Before the introduction of hooks, functional components lacked lifecycle methods. With hooks, they can now utilize lifecycle methods through useEffect.\n4. In terms of performance, class components entail slightly more overhead due to the additional complexity of class instantiation. However, in modern React applications with performance optimizations, the impact is often negligible.\n5. Functional components are generally considered more concise and readable. They are easier to understand and write, thanks to their reduced boilerplate code.\n\n# Why is it important to use the key attribute when using map in React?\n\nIn React, the key attribute is used when rendering a list of elements, typically with the map function, to help React identify which items have changed, been added, or been removed. The key should be a unique identifier for each element in the list.\n\nReact uses the key attribute to optimize the updating of the virtual DOM. When a list changes, React compares the new list with the previous one using keys. This allows React to efficiently update only the elements that have changed or are new, rather than re-rendering the entire list.\n\n```js\nconst myList = ['item1', 'item2', 'item3'];\n\nconst listItems = myList.map((item) =\u003e \u003cli key={item}\u003e{item}\u003c/li\u003e);\n```\n\n# What is JSX?\n\nJSX is a syntax extension for JavaScript recommended by React. It looks similar to XML/HTML, but it allows you to write JavaScript code within your JavaScript files. JSX makes it more convenient to describe what the UI should look like. React elements are typically created using JSX. For example, the JSX code:\n\n```js\nconst element = \u003ch1\u003eHello, JSX!\u003c/h1\u003e;\n```\n\nis transpiled by Babel into the following JavaScript code:\n\n```js\nconst element = React.createElement('h1', null, 'Hello, JSX!');\n```\n\nThe `React.createElement` function is a fundamental part of React and is used to create React elements. It takes the element type, props (attributes), and children as arguments.\n\n# What is the React Component Lifecycle?\n\nThe Three Main Phases in a component lifecycle are:\n\n1. **Mounting Phase:** This phase occurs when a component is initially created and inserted into the DOM.\n2. **Updating Phase:** This phase occurs when a component's state or props change, causing it to re-render.\n3. **Unmounting Phase:** This phase occurs when a component is removed from the DOM.\n\n# What are Higher Order Components in React?\n\nHigher Order Components (HOCs) are a pattern in React, a popular JavaScript library for building user interfaces. They are functions that take a component and return a new component with enhanced functionality. The term \"higher order\" comes from functional programming, where functions can take other functions as arguments or return them as results. HOCs provide a way to reuse component logic, share code between components, and abstract common functionality. For example see this code:\n\n```js\nimport React, { useEffect, useState } from 'react';\nimport { Redirect } from 'react-router-dom';\n\n// Higher Order Component for Authentication\nconst withAuth = (WrappedComponent) =\u003e {\n  return (props) =\u003e {\n    const [isAuthenticated, setIsAuthenticated] = useState(false);\n\n    useEffect(() =\u003e {\n      const checkAuthentication = async () =\u003e {\n        // Logic for checking authentication\n        const isAuthenticated = /* Check if user is authenticated */ true;\n        setIsAuthenticated(isAuthenticated);\n      };\n\n      checkAuthentication();\n    }, []);\n\n    if (isAuthenticated) {\n      // If authenticated, render the wrapped component\n      return \u003cWrappedComponent {...props} /\u003e;\n    } else {\n      // If not authenticated, redirect to the login page\n      return \u003cRedirect to='/login' /\u003e;\n    }\n  };\n};\n\nconst HomePage = () =\u003e \u003cdiv\u003eWelcome to the Home Page!\u003c/div\u003e;\nconst AuthenticatedHomePage = withAuth(HomePage);\n```\n\nThe code defines a reusable function that can wrap around a React component. This wrapper function `withAuth`, checks whether a user is authenticated. If authenticated, it renders the original component; if not, it redirects to a login page.\n\n# What is the useMemo hook?\n\n`useMemo` is a React Hook that lets you cache the result of a calculation between re-renders.\n\n```js\nconst cachedValue = useMemo(calculateValue, dependencies);\n```\n\n`calculateValue` is the function calculating the value that you want to cache. It should be pure, should take no arguments, and should return a value of any type. React will call your function during the initial render. On next renders, React will return the same value again if the `dependencies` have not changed since the last render. Otherwise, it will call `calculateValue`, return its result, and store it so it can be reused later.\n\nFor example:\n\n```js\nimport { useMemo } from 'react';\n\nfunction TodoList({ todos, tab }) {\n  const visibleTodos = useMemo(() =\u003e filterTodos(todos, tab), [todos, tab]);\n}\n```\n\n# What is Lifting State Up in React?\n\nLifting State Up is a pattern in React where the state is moved to a higher-level (parent) component from its child components. This is done to share state among sibling components or to allow a common ancestor to control the state of multiple components.\n\n```js\n// Parent.js\nimport React, { useState } from 'react';\nimport ChildA from './ChildA';\nimport ChildB from './ChildB';\n\nfunction Parent() {\n  const [sharedState, setSharedState] = useState('');\n\n  const handleStateChange = (newState) =\u003e {\n    setSharedState(newState);\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cChildA sharedState={sharedState} onStateChange={handleStateChange} /\u003e\n      \u003cChildB sharedState={sharedState} /\u003e\n    \u003c/div\u003e\n  );\n}\n\n// ChildA.js\nimport React from 'react';\n\nfunction ChildA({ sharedState, onStateChange }) {\n  const handleChange = (e) =\u003e {\n    onStateChange(e.target.value);\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cinput type='text' value={sharedState} onChange={handleChange} /\u003e\n    \u003c/div\u003e\n  );\n}\n\n// ChildB.js\nimport React from 'react';\n\nfunction ChildB({ sharedState }) {\n  return (\n    \u003cdiv\u003e\n      \u003cp\u003eShared State: {sharedState}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n# What is children prop?\n\nIn React, the children prop is a special prop that can be used to pass components or elements as children to another component. It allows a parent component to include arbitrary children components or elements within its JSX. The content passed as children is then accessible within the parent component using props.children. This makes it flexible for creating reusable and compositional components.\n\n# What are Pure Components?\n\nPure Components in React are a specific type of React component that automatically implements the shouldComponentUpdate lifecycle method with a shallow prop and state comparison. This means that a Pure Component will not re-render unless the actual data passed to it has changed. Pure Components can help optimize performance by preventing unnecessary renders when the component's output would be the same.\n\n# What are portals in React?\n\nPortals in React provide a way to render children components outside the DOM hierarchy of the parent component. Portals allow you to render components at a different DOM node than their parent, without affecting the parent's styles or behavior.\n\n# When should we use fragments compared to divs?\n\nFragments in React are a lightweight way to group multiple elements without introducing an additional wrapping div to the DOM. Using fragments `(\u003c\u003e...\u003c/\u003e)` helps avoid unnecessary and potentially undesirable nesting of elements. This is particularly beneficial when you want to keep your DOM structure clean and minimal, especially in cases where a wrapping div might interfere with styles or cause unintended layout effects.\n\n# What are error boundaries in React?\n\nError boundaries are React components that catch JavaScript errors anywhere in their component tree and log those errors, display a fallback UI, and prevent the error from crashing the entire component tree. They are implemented using the componentDidCatch lifecycle method.\n\nExample of an error boundary component:\n\n```js\nclass ErrorBoundary extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { hasError: false };\n  }\n\n  componentDidCatch(error, errorInfo) {\n    this.setState({ hasError: true });\n    // Log the error to an error reporting service\n  }\n\n  render() {\n    if (this.state.hasError) {\n      return \u003ch1\u003eSomething went wrong.\u003c/h1\u003e;\n    }\n    return this.props.children;\n  }\n}\n```\n\nAlso, this is possible in class based components only at the moment. There is currently no way to write an error boundary as a function component. You can use `react-error-boundary` package though.\n\n# What is the useCallback Hook?\n\nuseCallback is a hook that returns a memoized callback. In the context of React, a callback is often used as an event handler or to pass data between components. The useCallback hook takes two arguments: a function and a dependency array. It will return a memoized version of the function that only changes if one of the dependencies has changed.\n\nThis hook ensures that the callback function is only re-created if its dependencies change. This can be useful if a component is re-rendered frequently, as it can help to prevent the function from being unnecessarily re-created.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frabi-siddique%2Freact-js-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frabi-siddique%2Freact-js-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frabi-siddique%2Freact-js-interview-questions/lists"}