{"id":136308,"date":"2024-06-25T03:11:03","date_gmt":"2024-06-25T03:11:03","guid":{"rendered":"https:\/\/www.sushilkumar.ind.in\/blog\/?page_id=136308"},"modified":"2024-06-26T11:16:43","modified_gmt":"2024-06-26T11:16:43","slug":"reactjs-high-level-interview-question-and-answer","status":"publish","type":"page","link":"https:\/\/www.sushilkumar.ind.in\/blog\/reactjs-high-level-interview-question-and-answer\/","title":{"rendered":"ReactJS high-level interview question and answer"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">What is HOC(Higher order component)?<\/h2>\n\n\n\n<p>A Higher Order Component (HOC) in React is a pattern where a function takes a component and returns a new component with enhanced functionality. It&#8217;s a way to reuse component logic.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React from 'react';\n\n\/\/ Higher Order Component function\nconst withUpperCase = (WrappedComponent) =&gt; {\n  \/\/ Return a functional component\n  return function WithUpperCase(props) {\n    const { text } = props;\n    const upperCaseText = text.toUpperCase();\n\n    \/\/ Render the WrappedComponent with enhanced props\n    return &lt;WrappedComponent {...props} upperCaseText={upperCaseText} \/&gt;;\n  };\n};\n\n\/\/ Example function component to be enhanced\nconst DisplayText = ({ text, upperCaseText }) =&gt; {\n  return (\n    &lt;div&gt;\n      &lt;p&gt;Original Text: {text}&lt;\/p&gt;\n      &lt;p&gt;Uppercase Text: {upperCaseText}&lt;\/p&gt;\n    &lt;\/div&gt;\n  );\n};\n\n\/\/ Enhance DisplayText with withUpperCase HOC\nconst DisplayTextWithUpperCase = withUpperCase(DisplayText);\n\n\/\/ Usage example\nconst App = () =&gt; {\n  return (\n    &lt;div&gt;\n      &lt;DisplayTextWithUpperCase text=\"Hello, World!\" \/&gt;\n    &lt;\/div&gt;\n  );\n};\n\nexport default App;\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>In this example:\n\nwithUpperCase is a Higher Order Component that takes a function component (DisplayText) as an argument and returns a new function component (WithUpperCase).\nWithUpperCase function component computes upperCaseText by converting text prop to uppercase and then renders the WrappedComponent (DisplayText) with this enhanced prop.\nDisplayText is a simple function component that displays both the original and uppercase text.\nDisplayTextWithUpperCase is the enhanced component created by applying the withUpperCase HOC to DisplayText.\nApp component demonstrates the usage of DisplayTextWithUpperCase.\nThis example showcases how you can create a Higher Order Component for a function component using a functional approach with hooks like useState or useEffect as needed.<\/code><\/pre>\n\n\n\n<p>Higher Order Components allow for separation of concerns and reusability of component logic across different parts of your application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Concepts of shallow copy and deep copy with simple examples in JavaScript.<\/h2>\n\n\n\n<p><strong>Shallow Copy:<\/strong><\/p>\n\n\n\n<p>A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, it creates a new object, but the nested objects within it are still referenced from the original object. Shallow copies duplicate as little as possible.<\/p>\n\n\n\n<p><strong>Example of Shallow Copy:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Original object\nconst originalObject = {\n  name: 'John',\n  age: 30,\n  address: {\n    city: 'New York',\n    country: 'USA'\n  }\n};\n\n\/\/ Creating a shallow copy using Object.assign() or spread operator\nconst shallowCopy = { ...originalObject };\n\n\/\/ Modifying the shallow copy\nshallowCopy.name = 'Alice';\nshallowCopy.address.city = 'San Francisco'; \/\/ This will affect the originalObject's address as well\n\nconsole.log(originalObject);\nconsole.log(shallowCopy);\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>In the example above:\n\noriginalObject has a nested address object.\nshallowCopy is created using the spread operator (...) to shallowly copy originalObject.\nModifying shallowCopy.name affects only shallowCopy, but modifying shallowCopy.address.city also affects originalObject because the address object is shared (not deeply copied).<\/code><\/pre>\n\n\n\n<p><strong>Deep Copy:<\/strong><\/p>\n\n\n\n<p>A deep copy, on the other hand, creates a new collection object and recursively adds copies of nested child objects found in the original. It means duplicating every level of nested objects, so changes in the copy do not affect the original.<\/p>\n\n\n\n<p><strong>Example of Deep Copy:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Original object\nconst originalObject = {\n  name: 'John',\n  age: 30,\n  address: {\n    city: 'New York',\n    country: 'USA'\n  }\n};\n\n\/\/ Creating a deep copy using JSON methods (stringify and parse)\nconst deepCopy = JSON.parse(JSON.stringify(originalObject));\n\n\/\/ Modifying the deep copy\ndeepCopy.name = 'Alice';\ndeepCopy.address.city = 'San Francisco'; \/\/ This will NOT affect the originalObject's address\n\nconsole.log(originalObject);\nconsole.log(deepCopy);\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>In this example:\n\ndeepCopy is created by first converting originalObject to a JSON string (JSON.stringify(originalObject)), then parsing it back into an object (JSON.parse(...)). This ensures that all nested objects are deeply copied.\nModifying deepCopy.name or deepCopy.address.city does not affect originalObject because all nested objects are separate instances.<\/code><\/pre>\n\n\n\n<p><strong>Key Differences:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Shallow Copy:<\/strong> Only the immediate properties of the object are duplicated, including references to nested objects. Changes to nested objects in the shallow copy affect the original object.<\/li>\n\n\n\n<li><strong>Deep Copy:<\/strong> All properties and nested objects are duplicated recursively, ensuring changes to the copy do not affect the original object.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How to pass data child to parent component in react?<\/h2>\n\n\n\n<p>In React, passing data from a child component to a parent component involves lifting state up from the child to the parent. This is necessary because React&#8217;s data flow is typically unidirectional (from parent to child). Here\u2019s how you can achieve this:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Method 1: Callbacks as Props<\/h3>\n\n\n\n<p>The most common way to pass data from child to parent in React is by passing a callback function as a prop from the parent to the child. The child component can then call this callback function and pass data back to the parent.<\/p>\n\n\n\n<p><strong>Parent Component:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from 'react';\nimport ChildComponent from '.\/ChildComponent';\n\nconst ParentComponent = () =&gt; {\n  const &#91;dataFromChild, setDataFromChild] = useState('');\n\n  \/\/ Callback function to receive data from child\n  const handleDataFromChild = (data) =&gt; {\n    setDataFromChild(data);\n  };\n\n  return (\n    &lt;div&gt;\n      &lt;h2&gt;Parent Component&lt;\/h2&gt;\n      &lt;p&gt;Data from Child: {dataFromChild}&lt;\/p&gt;\n      &lt;ChildComponent sendDataToParent={handleDataFromChild} \/&gt;\n    &lt;\/div&gt;\n  );\n};\n\nexport default ParentComponent;\n<\/code><\/pre>\n\n\n\n<p><strong>Child Component (ChildComponent):<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React from 'react';\n\nconst ChildComponent = ({ sendDataToParent }) =&gt; {\n  const handleClick = () =&gt; {\n    \/\/ Simulating data passed from child to parent\n    const data = 'Data sent from child component';\n    sendDataToParent(data); \/\/ Call the callback function from props\n  };\n\n  return (\n    &lt;div&gt;\n      &lt;h3&gt;Child Component&lt;\/h3&gt;\n      &lt;button onClick={handleClick}&gt;Send Data to Parent&lt;\/button&gt;\n    &lt;\/div&gt;\n  );\n};\n\nexport default ChildComponent;\n<\/code><\/pre>\n\n\n<h3>Explanation:<\/h3>\n<ol>\n<li>\n<p><strong>Parent Component:<\/strong><\/p>\n<ul>\n<li>Defines a state variable <strong>dataFromChild<\/strong> to store data received from the child.<\/li>\n<li>Declares a callback function <strong>handleDataFromChild<\/strong> that updates <strong>dataFromChild<\/strong> with the received data.<\/li>\n<li>Passes <strong>handleDataFromChild<\/strong> as a prop (<strong>sendDataToParent<\/strong>) to the <strong>ChildComponent<\/strong>.<\/li>\n<\/ul>\n<\/li>\n<li>\n<p><strong>Child Component:<\/strong><\/p>\n<ul>\n<li>Receives <strong>sendDataToParent<\/strong> as a prop from the parent.<\/li>\n<li>Defines an event handler (<strong>handleClick<\/strong>) that triggers when a button is clicked (or any other event occurs).<\/li>\n<li>Inside <strong>handleClick<\/strong>, it calls <strong>sendDataToParent<\/strong> with the data you want to pass back to the parent.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n<h3 class=\"wp-block-heading\">Alternative Methods:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Context API:<\/strong> For passing data through multiple layers of components without manually passing props down through each level.<\/li>\n\n\n\n<li><strong>State Management Libraries (like Redux):<\/strong> For managing global state and sharing data between components without relying on direct parent-child relationships.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What is Controlled and uncontrolled components in react with example?<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Controlled Components<\/h3>\n\n\n\n<p>Controlled components are React components that manage their state internally and update it based on user input. They receive their current value through props and notify changes through callbacks like <code>onChange<\/code>.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from 'react';\n\nfunction ControlledInput() {\n  const &#91;value, setValue] = useState('');\n\n  const handleChange = (event) => {\n    setValue(event.target.value);\n  };\n\n  return (\n    &lt;input\n      type=\"text\"\n      value={value}\n      onChange={handleChange}\n    \/>\n  );\n}\n\nexport default ControlledInput;\n<\/code><\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul>\n<li>The <strong>ControlledInput<\/strong> component uses the <strong>useState<\/strong> hook to maintain the <strong>value<\/strong> state internally.<\/li>\n\n\n\n<li>The <strong>&lt;input&gt;<\/strong> element is controlled because its value is determined by the <strong>value<\/strong> state variable.<\/li>\n\n\n\n<li><strong>handleChange<\/strong> function updates the <strong>value<\/strong> state whenever the input changes, ensuring that React manages and reflects the current state of the input field.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Uncontrolled Components<\/h3>\n\n\n\n<p>Uncontrolled components in React rely on the DOM to manage and store their state. They often use refs to directly access the DOM elements to retrieve their current values.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useRef } from 'react';\n\nfunction UncontrolledInput() {\n  const inputRef = useRef(null);\n\n  const handleSubmit = (event) => {\n    event.preventDefault();\n    console.log(inputRef.current.value); \/\/ Accessing input value directly\n  };\n\n  return (\n    &lt;form onSubmit={handleSubmit}>\n      &lt;input\n        type=\"text\"\n        ref={inputRef}\n      \/>\n      &lt;button type=\"submit\">Submit&lt;\/button>\n    &lt;\/form>\n  );\n}\n\nexport default UncontrolledInput;\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Explanation:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The <strong>UncontrolledInput<\/strong> component uses a ref (<strong>inputRef<\/strong>) to directly access the DOM node of the input element.<\/li>\n\n\n\n<li>When the form is submitted, <strong>handleSubmit<\/strong> function logs the current value of the input directly from the DOM using <strong>inputRef.current.value<\/strong>.<\/li>\n\n\n\n<li>React does not manage the state of the input field; it&#8217;s managed by the DOM itself, making it an uncontrolled component.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Key Differences:<\/h3>\n\n\n\n<ul>\n<li><strong>State Management:<\/strong> Controlled components manage state within React components using state variables (like <strong>useState<\/strong>).<\/li>\n\n\n\n<li><strong>DOM Interaction:<\/strong> Uncontrolled components rely on direct DOM manipulation and typically use refs to interact with DOM nodes.<\/li>\n\n\n\n<li><strong>Event Handling:<\/strong> Controlled components use React&#8217;s synthetic events (<strong>onChange<\/strong>, <strong>onClick<\/strong>) to handle user interactions. Uncontrolled components may use traditional DOM events (<strong>onSubmit<\/strong>, <strong>onClick<\/strong>) and directly access DOM properties like <strong>value<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Write a simple React program that fetches data from an API, displays it in a table, and allows users to delete individual records by clicking a delete button next to each row.<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState, useEffect } from 'react';\n\nconst DataTable = () => {\n  const &#91;data, setData] = useState(&#91;]);\n\n  useEffect(() => {\n    fetchData();\n  }, &#91;]);\n\n  const fetchData = async () => {\n    try {\n      const response = await fetch('https:\/\/jsonplaceholder.typicode.com\/users');\n      if (!response.ok) {\n        throw new Error('Network response was not ok');\n      }\n      const json = await response.json();\n      setData(json);\n    } catch (error) {\n      console.error('Error fetching data: ', error);\n    }\n  };\n\n  const handleDelete = (id) => {\n    const updatedData = data.filter((item) => item.id !== id);\n    setData(updatedData);\n  };\n\n  return (\n    &lt;div>\n      &lt;h2>Users&lt;\/h2>\n      &lt;table>\n        &lt;thead>\n          &lt;tr>\n            &lt;th>Name&lt;\/th>\n            &lt;th>Email&lt;\/th>\n            &lt;th>Company&lt;\/th>\n            &lt;th>Action&lt;\/th>\n          &lt;\/tr>\n        &lt;\/thead>\n        &lt;tbody>\n          {data.map((user) => (\n            &lt;tr key={user.id}>\n              &lt;td>{user.name}&lt;\/td>\n              &lt;td>{user.email}&lt;\/td>\n              &lt;td>{user.company.name}&lt;\/td>\n              &lt;td>\n                &lt;button onClick={() => handleDelete(user.id)}>Delete&lt;\/button>\n              &lt;\/td>\n            &lt;\/tr>\n          ))}\n        &lt;\/tbody>\n      &lt;\/table>\n    &lt;\/div>\n  );\n};\n\nexport default DataTable;\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation:<\/h3>\n\n\n\n<ul>\n<li><strong>DataTable Component<\/strong>:\n<ul class=\"wp-block-list\">\n<li><strong>useState<\/strong>: <strong>data<\/strong> state holds the fetched user data from the API.<\/li>\n\n\n\n<li><strong>useEffect<\/strong>: Fetches data from <code>https:\/\/jsonplaceholder.typicode.com\/users<\/code> when the component mounts.<\/li>\n\n\n\n<li><strong>fetchData<\/strong>: Fetches data from the API and updates the <strong>data<\/strong> state.<\/li>\n\n\n\n<li><strong>handleDelete<\/strong>: Removes a user from the <strong>data<\/strong> state array when the delete button is clicked.<\/li>\n\n\n\n<li><strong>Render<\/strong>: Maps over the <strong>data<\/strong> array to display each user in a table row. Each row has a delete button that calls <strong>handleDelete<\/strong> with the user&#8217;s <strong>id<\/strong>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>App Component<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Imports and renders the <strong>DataTable<\/strong> component, which encapsulates the table and delete functionality.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Notes:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>This example uses <code>fetch<\/code> for making HTTP requests. You can replace the URL in <code>fetchData<\/code> with your own API endpoint.<\/li>\n\n\n\n<li>Error handling for the fetch operation and other edge cases (like empty responses) should ideally be added for production-ready applications.<\/li>\n\n\n\n<li>Ensure you handle state updates and API interactions according to your application&#8217;s requirements and best practices.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>What is HOC(Higher order component)? A Higher Order Component (HOC) in React is a pattern where a function takes a component and returns a new component with enhanced functionality. It&#8217;s a way to reuse component logic. Example: import React from &#8216;react&#8217;; \/\/ Higher Order Component function const withUpperCase = (WrappedComponent) =&gt; { \/\/ Return a &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"jetpack_post_was_ever_published":false,"footnotes":""},"class_list":["post-136308","page","type-page","status-publish",""],"acf":[],"aioseo_notices":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/P99pkJ-zsw","_links":{"self":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/pages\/136308"}],"collection":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/comments?post=136308"}],"version-history":[{"count":16,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/pages\/136308\/revisions"}],"predecessor-version":[{"id":136336,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/pages\/136308\/revisions\/136336"}],"wp:attachment":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/media?parent=136308"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}