Ace Your React Interview: Comprehensive Guide & Key Concepts
Tags: react, javascript
Published: 2023-10-25 22:42:56

---
title: Ace Your React Interview: Comprehensive Guide & Key Concepts
published: true
description: Within this guide, you'll find a curated collection of over 30 pivotal questions that frequently surface in React interviews.
tags: react, javascript
cover_image: https://montedelgallo.com/wp-content/uploads/react-interview-scaled.jpeg
# Use a ratio of 100:42 for best results.
published_at: current
---

In today's competitive tech landscape, a successful interview often hinges not just on your skills, but on your preparation. React, as one of the leading libraries in front-end development, frequently sits at the center of such interviews, and the questions can range from basic to deeply intricate. "Ace Your React Interview: Comprehensive Guide &amp; Key Concepts" is tailored for those aspiring to shine in such pivotal moments.

Within this guide, you'll find a curated collection of over 30 pivotal questions that frequently surface in React interviews. But, more than just questions, we provide you with succinct, articulate answers that showcase a profound understanding of React's core principles and advanced nuances. Think of this not just as a study guide, but as a blueprint to articulate your React expertise confidently and convincingly. Whether you're an experienced developer aiming to refresh your knowledge, or you're stepping into the React realm for the first time, this guide is your ally. Let's ensure that when the spotlight is on, you're not only ready but poised to impress.
<h2>Questions</h2>
<ul>
 	<li>Explain what is the Virtual DOM in React</li>
 	<li>What are the differences between the Virtual DOM and the DOM?</li>
 	<li>What is JSX?</li>
 	<li>What do you understand when we talk about Render in React?</li>
 	<li>Explain the concept of Components in React</li>
 	<li>What are props in React and what are the main differences with state?</li>
 	<li>Props:</li>
 	<li>State:</li>
 	<li>How can you update the state of a component?</li>
 	<li>Class Components:</li>
 	<li>Functional Components:</li>
 	<li>What are synthethic events in React?</li>
 	<li>What are refs in React, give an example of when would you use one.</li>
 	<li>How does React render process work?</li>
 	<li>What are keys in React and why are they important?</li>
 	<li>How can you reuse logic in functional components?</li>
 	<li>What is the difference between a controlled and uncontrolled component in React?</li>
 	<li>Explain the main difference between server side rendering and client side rendering in React</li>
 	<li>How would you avoid unnecessary renders in a React component?</li>
 	<li>What is a Portal in React?</li>
 	<li>State the main difference between useEffect and useLayoutEffect</li>
 	<li>Where do you usually fetch data in React?</li>
 	<li>What are hooks in React?</li>
 	<li>If you wanted a component to perform an action only once when the component initially rendered how would you achieve it</li>
 	<li>with a function component?</li>
 	<li>What is prop-drilling, and how can you avoid it?</li>
 	<li>How can you reset a component’s state to its initial state?</li>
 	<li>Explain the difference between useState and useEffect.</li>
 	<li>If you have to set a key value in a component, from where would you get that value?</li>
 	<li>Explain the concept of lazy loading React components</li>
 	<li>Explain the main differences between useMemo and useCallback</li>
 	<li>Why would you ever use forwardRef in React?</li>
 	<li>At what point does the useEffect cleanup function run?</li>
 	<li>Explain the concept of Reducers and Context in React</li>
 	<li>How would you catch render errors in React components at the global scope?</li>
 	<li>How does useEffect check changes in its array dependency?</li>
</ul>
<h3>Explain what is the Virtual DOM in React</h3>
The <strong>Virtual DOM</strong> in React is a <strong>lightweight representation</strong> of the actual DOM elements. The rendering engine can quickly make changes to the Virtual DOM and then subsequently update the real DOM in a more efficient and optimized way. The primary benefit is that it <strong>minimizes direct manipulations</strong> of the actual DOM, resulting in <strong>faster and smoother updates</strong> to the user interface.
<h3>What are the differences between the Virtual DOM and the DOM?</h3>
The <strong>Virtual DOM</strong> and the <strong>DOM</strong> are both critical concepts in web development, especially when working with React. Here are their primary differences:
<ul>
 	<li><strong>Representation:</strong> The <strong>DOM</strong> (Document Object Model) is a programming interface and structured representation of a webpage, allowing developers to interact with and manipulate the page content, structure, and styles. On the other hand, the <strong>Virtual DOM</strong> is a <strong>lightweight</strong> copy of the actual DOM in React, which helps in determining the most efficient way to update the real DOM.</li>
 	<li><strong>Efficiency:</strong> Directly manipulating the DOM can be slow and inefficient, especially with frequent changes. The <strong>Virtual DOM</strong> enables React to determine the minimal number of DOM changes required by comparing the current Virtual DOM with the next version (a process called <strong>diffing</strong>) and then applying only the necessary updates.</li>
 	<li><strong>Existence:</strong> While the <strong>DOM</strong> is a standard that exists in all web browsers, the <strong>Virtual DOM</strong> is specific to React and certain other modern web libraries or frameworks.</li>
</ul>
Here's a basic code illustration to emphasize the concept:
<pre><code>
// Traditional DOM manipulation:
const element = document.createElement('div');
element.textContent = 'Hello, DOM!';
document.body.appendChild(element);

// React's way using Virtual DOM:
import React from 'react';
function App() {
    return &lt;div&gt;Hello, Virtual DOM!&lt;/div&gt;;
}
</code></pre>
<h3>What is JSX?</h3>
<strong>JSX</strong>, or JavaScript XML, is a syntax extension for JavaScript, predominantly used with React. It allows developers to write HTML-like code within their JavaScript code, leading to a more intuitive and readable way to describe the UI components.
<ul>
 	<li><strong>Combination:</strong> JSX essentially allows you to combine JavaScript and HTML. This synergy makes it easier to visualize the UI structure directly within the component logic.</li>
 	<li><strong>Transpilation:</strong> Browsers don't natively understand JSX. Therefore, tools like <strong>Babel</strong> are used to transpile JSX into regular JavaScript code that browsers can interpret.</li>
 	<li><strong>Components:</strong> With JSX, React components can be defined using a syntax that's visually similar to HTML, making it straightforward to define and understand the component's structure.</li>
</ul>
Here's a simple illustration of JSX in action:
<pre><code>
// Without JSX:
React.createElement('div', { className: 'greeting' }, 'Hello, world!');

// With JSX:
&lt;div className="greeting"&gt;Hello, world!&lt;/div&gt;
</code></pre>
Notice how the JSX version is more concise and resembles traditional HTML, offering better readability.
<h3>What do you understand when we talk about Render in React?</h3>
In React, when we talk about <strong>render</strong>, we are referring to the process of translating the application's state and props into a visual representation within the browser. Rendering determines how the UI should look based on the data available to the component.
<ul>
 	<li><strong>Initial Render:</strong> The first time a React component is added to the DOM, it undergoes an initial render, creating the visual output for the user.</li>
 	<li><strong>Re-rendering:</strong> When there are changes in the component's state or props, React determines if an update to the UI is required. If needed, a re-render is triggered to reflect the changes.</li>
 	<li><strong>Virtual DOM:</strong> Instead of making direct changes to the real DOM, React first updates the Virtual DOM. It then compares (or "diffs") the current Virtual DOM with the new one and calculates the most efficient way to make changes to the real DOM.</li>
</ul>
Here's a basic example illustrating the rendering process in a React component:
<pre><code>
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    &lt;div&gt;
      &lt;p&gt;You clicked {count} times&lt;/p&gt;
      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;
        Click me
      &lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
Every time the button in the <code>Counter</code> component is clicked, the state (<code>count</code>) changes, which triggers a re-render to update the displayed click count.
<h3>Explain the concept of Components in React</h3>
In React, <strong>Components</strong> are the building blocks of the user interface. They allow you to split the UI into independent, reusable pieces, and think about each piece in isolation. Components can be likened to custom HTML elements with their own structure, logic, and behavior.
<ul>
 	<li><strong>Reusable:</strong> Components can be reused across different parts of an application. This promotes a DRY (Don't Repeat Yourself) principle.</li>
 	<li><strong>Stateful and Stateless:</strong> Components can either maintain their own data state (stateful) or receive data entirely through props (stateless).</li>
 	<li><strong>Class and Functional:</strong> Historically, components were primarily class-based, but with the introduction of React hooks, functional components can now manage state and side effects as well.</li>
 	<li><strong>Composition:</strong> Components can be nested within other components, enabling the creation of more complex UIs through composition.</li>
</ul>
Here's a basic example of a React component:
<pre><code>
// Functional Component
function Greeting(props) {
  return &lt;h1&gt;Hello, {props.name}!&lt;/h1&gt;;
}
</code></pre>
And using the component:
<pre><code>
&lt;Greeting name="John" /&gt;
</code></pre>
This would render the text "Hello, John!" on the screen. The component encapsulates the logic and structure needed to create this piece of the UI, making it easy to reuse wherever a greeting is needed.
<h3>What are props in React and what are the main differences with state?</h3>
In React, <strong>props</strong> (short for "properties") and <strong>state</strong> are two key concepts that help manage data in a component. While they both hold information that influences the output of a render, they serve different purposes and have distinct characteristics.
<h3>Props:</h3>
<ul>
 	<li><strong>Immutable:</strong> Props are <strong>read-only</strong>. This means a component should never modify its own props.</li>
 	<li><strong>Passed from Parent:</strong> Props are passed to a component from its parent component. They allow components to communicate with each other.</li>
 	<li><strong>External Data:</strong> Think of props as arguments or parameters you pass to a function.</li>
</ul>
<h3>State:</h3>
<ul>
 	<li><strong>Mutable:</strong> State is <strong>changeable</strong> data. When state changes in a component, the component re-renders.</li>
 	<li><strong>Internal Data:</strong> State represents data that a component's event handlers may change to trigger a user interface update.</li>
 	<li><strong>Lifecycle:</strong> State can have a lifecycle, with mounting, updating, and unmounting phases.</li>
</ul>
Highlighting the differences:
<pre><code>
// Using props
function Welcome(props) {
  return &lt;h1&gt;Hello, {props.name}&lt;/h1&gt;;
}

// Using state
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  increment = () =&gt; {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      &lt;div&gt;
        &lt;p&gt;Count: {this.state.count}&lt;/p&gt;
        &lt;button onClick={this.increment}&gt;Increment&lt;/button&gt;
      &lt;/div&gt;
    );
  }
}
</code></pre>
In the first example, the <code>Welcome</code> component receives the name to display via props. In the second example, the <code>Counter</code> component maintains its own count in the state, which can be changed using the increment function.
<h3>How can you update the state of a component?</h3>
Updating the <strong>state</strong> of a component in React is crucial for ensuring that the user interface remains in sync with the underlying data. In React, you should never directly modify the state. Instead, you use the <strong>setState</strong> method (in class components) or the <strong>useState</strong> hook (in functional components) to update the state.
<h3>Class Components:</h3>
In class components, the <strong>setState</strong> method is used:
<pre><code>
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleIncrement = () =&gt; {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      &lt;div&gt;
        &lt;p&gt;Count: {this.state.count}&lt;/p&gt;
        &lt;button onClick={this.handleIncrement}&gt;Increment&lt;/button&gt;
      &lt;/div&gt;
    );
  }
}
</code></pre>
<h3>Functional Components:</h3>
In functional components, the <strong>useState</strong> hook is commonly used to manage state:
<pre><code>
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const handleIncrement = () =&gt; {
    setCount(count + 1);
  }

  return (
    &lt;div&gt;
      &lt;p&gt;Count: {count}&lt;/p&gt;
      &lt;button onClick={handleIncrement}&gt;Increment&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
In both examples, the state update functions (<strong>setState</strong> and <strong>setCount</strong>) trigger a re-render of the component, ensuring the displayed count reflects the updated state.
<h3>What are synthethic events in React?</h3>
In React, <strong>Synthetic Events</strong> are wrappers around the browser's native events. They aim to provide a consistent event system across different browsers, ironing out any inconsistencies and ensuring a unified behavior in your application.
<ul>
 	<li><strong>Cross-Browser Compatibility:</strong> Synthetic Events encapsulate the behavior of native browser events, offering the same interface regardless of underlying browser differences.</li>
 	<li><strong>Performance:</strong> React reuses synthetic event objects for better performance. This reduces the overhead of creating a new event object for every event.</li>
 	<li><strong>Pooling:</strong> After the event callback has been invoked, React "pools" the synthetic events, nullifying their properties. This ensures a reduced memory footprint.</li>
 	<li><strong>Consistent Properties:</strong> Properties and methods on the synthetic event are consistent across different browsers.</li>
</ul>
Here's an example showcasing the use of a synthetic event:
<pre><code>
import React from 'react';

function ClickableComponent() {
  const handleClick = (event) =&gt; {
    event.preventDefault(); // Using a synthetic event method
    console.log(event.type); // Outputs: "click"
  }

  return (
    &lt;a href="https://www.example.com" onClick={handleClick}&gt;
      Click Me
    &lt;/a&gt;
  );
}
</code></pre>
In the example above, the <code>handleClick</code> function receives a synthetic event object when the link is clicked. This ensures that the event behavior is consistent, no matter which browser the code runs in.
<h3>What are refs in React, give an example of when would you use one.</h3>
In React, <strong>refs</strong> (short for "references") provide a way to directly access the DOM elements or React elements created in the render method. This is useful in cases where you need to bypass the typical data flow mechanisms of React, such as when you need to focus an input element, trigger imperative animations, or integrate with third-party libraries.
<ul>
 	<li><strong>Direct Access:</strong> Refs allow direct access to DOM elements, which is generally discouraged in favor of a declarative approach, but can be essential in some situations.</li>
 	<li><strong>Avoid Overuse:</strong> It's important to avoid overusing refs. React's declarative approach usually negates the need for them. Use them as a last resort or in scenarios where their necessity is clear.</li>
 	<li><strong>createRef and useRef:</strong> Refs can be created using <code>React.createRef()</code> in class components and <code>useRef()</code> hook in functional components.</li>
</ul>
Here's an example showcasing the use of refs to focus on an input element:
<pre><code>
import React, { useRef, useEffect } from 'react';

function FocusInput() {
  // Create a ref object
  const inputRef = useRef(null);

  useEffect(() =&gt; {
    // Focus the input element when the component mounts
    inputRef.current.focus();
  }, []);

  return (
    &lt;input ref={inputRef} type="text" placeholder="I will be focused on mount" /&gt;
  );
}
</code></pre>
In this example, as soon as the <code>FocusInput</code> component mounts, the input element is automatically focused using the ref. This illustrates a common use-case for refs: controlling focus programmatically.
<h3>How does React render process work?</h3>
The <strong>React render process</strong> is a sequence of steps the library follows to convert React components into a visual representation in the browser. It's optimized for performance and ensures efficient updates to the UI. Here's a simplified breakdown:
<ol>
 	<li><strong>JSX Compilation:</strong> During the development phase, JSX (an XML-like syntax extension for JavaScript) is compiled into regular JavaScript using tools like Babel. It gets transformed into <code>React.createElement()</code> calls.</li>
 	<li><strong>Initial Render:</strong> When a React application starts, it goes through the initial rendering phase. All components return their defined output (typically other components, HTML elements, etc.).</li>
 	<li><strong>Virtual DOM Creation:</strong> React creates a lightweight representation of the output, known as the Virtual DOM. This allows React to determine changes in an optimized manner.</li>
 	<li><strong>Reconciliation:</strong> When there's a change in state or props, React triggers a re-render. Instead of updating the real DOM directly, React first updates the Virtual DOM.</li>
 	<li><strong>Diffing:</strong> React compares (or "diffs") the previous Virtual DOM with the new one to determine the most efficient series of changes.</li>
 	<li><strong>Committing Updates:</strong> After calculating the necessary changes, React updates the real DOM. This is the phase where users see updates on their screen.</li>
 	<li><strong>Batching:</strong> To further enhance performance, React batches multiple <code>setState()</code> calls together into a single update, reducing the number of DOM manipulations.</li>
 	<li><strong>Component Lifecycle:</strong> Throughout the render process, React components go through a series of lifecycle methods (in class components) or effects (in functional components with hooks) allowing developers to plug in code at specific points.</li>
</ol>
By following this process, React ensures the UI remains responsive and updates efficiently, avoiding unnecessary computations or DOM updates.
<h3>What are keys in React and why are they important?</h3>
In React, <strong>keys</strong> are special attributes you should provide when creating lists of elements. They help React identify which items have been added, changed, or removed, and they play a crucial role in optimizing the performance of updates, especially in lists or dynamic content.
<ul>
 	<li><strong>Identity:</strong> Keys give elements a stable identity. They should be unique among siblings but don't need to be globally unique.</li>
 	<li><strong>Reconciliation Process:</strong> During React's reconciliation (diffing) process, keys help to correctly match elements in the original tree structure with those in the subsequent tree.</li>
 	<li><strong>Performance:</strong> Without keys, React might need to re-render more components than necessary, leading to decreased performance.</li>
 	<li><strong>Stateful Components:</strong> Using keys ensures that the state associated with an item is maintained even when the order changes or items are added/removed.</li>
</ul>
Here's a basic example illustrating the use of keys:
<pre><code>
import React from 'react';

function ItemList(props) {
  const items = props.items;

  return (
    &lt;ul&gt;
      {items.map(item =&gt; 
        &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;
      )}
    &lt;/ul&gt;
  );
}
</code></pre>
In this example, each item has a unique <code>id</code> that is used as the key. This ensures that React can efficiently determine changes in the list and update the DOM accordingly.

<strong>Note:</strong> It's generally discouraged to use indexes as keys if the list can change over time. This can lead to bugs and negatively impact performance.
<h3>How can you reuse logic in functional components?</h3>
In React, when working with functional components, the primary way to reuse logic is through the use of <strong>custom hooks</strong>. Custom hooks allow you to extract component logic into reusable functions.
<ul>
 	<li><strong>Custom Hooks:</strong> They are JavaScript functions that can use other hooks. By convention, they start with the word <code>use</code>, and they allow you to share and reuse stateful logic across different components.</li>
 	<li><strong>Isolation:</strong> Custom hooks allow for better isolation and testing of logic, making your components cleaner and easier to maintain.</li>
 	<li><strong>Composition:</strong> Multiple custom hooks can be combined to create more complex functionality, making them composable.</li>
</ul>
Here's a simple example illustrating the use of custom hooks:
<pre><code>
import { useState } from 'react';

// Custom hook to handle input changes
function useInput(initialValue) {
  const [value, setValue] = useState(initialValue);
  const handleChange = (e) =&gt; {
    setValue(e.target.value);
  };

  return [value, handleChange];
}

function MyComponent() {
  const [username, handleUsernameChange] = useInput('');
  const [email, handleEmailChange] = useInput('');

  return (
    &lt;div&gt;
      &lt;input value={username} onChange={handleUsernameChange} placeholder="Username" /&gt;
      &lt;input value={email} onChange={handleEmailChange} placeholder="Email" /&gt;
    &lt;/div&gt;
  );
}
</code></pre>
In the example above, the <code>useInput</code> custom hook manages the state and change logic of an input field. By using this custom hook, we can avoid repeating the same logic for different input fields, showcasing the power of reusable logic in functional components.
<h3>What is the difference between a controlled and uncontrolled component in React?</h3>
In React, components that handle form elements can be classified into two categories: <strong>controlled</strong> and <strong>uncontrolled</strong> components.
<ul>
 	<li><strong>Controlled Components:</strong>
<ul>
 	<li>In a controlled component, the form data is managed by the React state. The value of the input is always driven by the React state.</li>
 	<li>Whenever there's a change in the input, a handler function (like <code>onChange</code>) is invoked to update the state, which in turn updates the input's value.</li>
 	<li>It offers more predictability and can be directly influenced by the component's state.</li>
</ul>
</li>
 	<li><strong>Uncontrolled Components:</strong>
<ul>
 	<li>In an uncontrolled component, the form data is managed by the DOM itself, not by the React state.</li>
 	<li>To get the value from an input in an uncontrolled component, you'd use a ref to directly access the DOM element.</li>
 	<li>They are similar to traditional HTML form inputs and might be simpler for integrating React with non-React code.</li>
</ul>
</li>
</ul>
Here's a comparison with examples:
<pre><code>
// Controlled Component
function ControlledInput() {
  const [value, setValue] = useState('');

  return (
    &lt;input value={value} onChange={e =&gt; setValue(e.target.value)} /&gt;
  );
}

// Uncontrolled Component
function UncontrolledInput() {
  const inputRef = useRef(null);

  const showAlert = () =&gt; {
    alert(inputRef.current.value);
  }

  return (
    &lt;div&gt;
      &lt;input ref={inputRef} /&gt;
      &lt;button onClick={showAlert}&gt;Show Value&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
Generally, controlled components are recommended in React as they allow for more predictable behavior and better integration with React's declarative nature.
<h3>Explain the main difference between server side rendering and client side rendering in React</h3>
In the context of React applications, rendering can occur either on the server or the client side. The choice between <strong>Server Side Rendering (SSR)</strong> and <strong>Client Side Rendering (CSR)</strong> can significantly impact performance, SEO, and user experience. Here are the primary differences:
<ul>
 	<li><strong>Server Side Rendering (SSR):</strong>
<ul>
 	<li>The React components are rendered on the server into a static HTML string.</li>
 	<li>Users see the content faster as the server sends the rendered page directly. This can result in a faster <strong>First Contentful Paint (FCP)</strong>.</li>
 	<li>It can be beneficial for SEO, as search engine crawlers receive a fully rendered page.</li>
 	<li>Popular frameworks like <strong>Next.js</strong> simplify the SSR process for React applications.</li>
 	<li>Requires a server to process requests, which can lead to increased server load.</li>
</ul>
</li>
 	<li><strong>Client Side Rendering (CSR):</strong>
<ul>
 	<li>The React components are rendered directly in the browser. Initially, the server sends a blank or loading page, and the actual content is populated as the JavaScript executes.</li>
 	<li>It might result in a slower initial page load, as the browser has to load, parse, and execute the JavaScript before displaying content.</li>
 	<li>Once loaded, navigating between pages or views can be faster due to the assets and React being already in memory.</li>
 	<li>SEO might be more challenging (though search engines have gotten better at indexing JavaScript applications).</li>
 	<li>Frameworks like <strong>Create React App</strong> set up CSR-based React applications.</li>
</ul>
</li>
</ul>
In practice, many applications leverage a combination of both, known as <strong>Hybrid Rendering</strong>, to optimize performance, SEO, and user experience. They may use SSR for the initial load and CSR for subsequent dynamic updates.
<h3>How would you avoid unnecessary renders in a React component?</h3>
Ensuring efficient rendering is key to maximizing the performance of React applications. Unnecessary renders can slow down the app and lead to a poor user experience. Here are ways to avoid them:
<ul>
 	<li><strong>Use PureComponent:</strong>
<ul>
 	<li>If you're using class components, extend <code>PureComponent</code> instead of <code>Component</code>. This ensures a shallow comparison of state and props, preventing unnecessary renders when data hasn't changed.</li>
</ul>
</li>
 	<li><strong>Utilize React.memo:</strong>
<ul>
 	<li>For functional components, wrap your component with <code>React.memo</code>. It's similar to <code>PureComponent</code> and does a shallow comparison of props.</li>
</ul>
</li>
 	<li><strong>Optimize state and props:</strong>
<ul>
 	<li>Ensure that you're only updating state or props when necessary. Avoid creating new references (objects or arrays) unless there's a change in the data.</li>
</ul>
</li>
 	<li><strong>Use Callbacks Wisely:</strong>
<ul>
 	<li>Use the <code>useCallback</code> hook to memoize callback functions, preventing them from being recreated every render.
<pre><code>
const increment = useCallback(() =&gt; {
  setCount(prevCount =&gt; prevCount + 1);
}, []);
</code></pre>
</li>
</ul>
</li>
 	<li><strong>Memoize Computations:</strong>
<ul>
 	<li>If you have computations derived from state or props, use the <code>useMemo</code> hook to ensure they're recalculated only when necessary.
<pre><code>
const doubledValue = useMemo(() =&gt; {
  return value * 2;
}, [value]);
</code></pre>
</li>
</ul>
</li>
 	<li><strong>Use Context Sparingly:</strong>
<ul>
 	<li>Remember that any value change in a <code>React.Context</code> will re-render all components consuming that context. Break contexts into smaller parts if possible or use libraries like <code>react-query</code> for more granular control.</li>
</ul>
</li>
 	<li><strong>Profile with DevTools:</strong>
<ul>
 	<li>Use the React DevTools' profiler to inspect which components are re-rendering and why. This helps in identifying bottlenecks and optimizing renders.</li>
</ul>
</li>
</ul>
By being mindful of renders and employing optimization techniques, you can ensure a smooth and responsive user experience.
<h3>What is a Portal in React?</h3>
In React, a <strong>Portal</strong> provides a way to render children outside the parent DOM hierarchy, yet it retains the same context and event bubbling behavior as if they were inside the parent. This is particularly useful for UI elements like modals, popups, and tooltips which might be visually positioned outside the component but need to stay within the React component logic.
<ul>
 	<li><strong>Advantages:</strong>
<ul>
 	<li>It can help with CSS styling issues, especially with z-index or overflow problems.</li>
 	<li>It ensures that the component's behavior remains consistent, even if visually rendered outside the main UI tree.</li>
</ul>
</li>
 	<li><strong>Usage:</strong>
<ul>
 	<li>React provides a <code>ReactDOM.createPortal()</code> method for this purpose.
<pre><code>
import ReactDOM from 'react-dom';

function Modal(props) {
  return ReactDOM.createPortal(
    &lt;div className="modal"&gt;
      {props.children}
    &lt;/div&gt;,
    document.getElementById('modal-root')
  );
}
</code></pre>
</li>
 	<li>In the example above, the <code>Modal</code> component renders its children into a <code>modal-root</code> DOM node outside the main app hierarchy.</li>
</ul>
</li>
</ul>
Using Portals efficiently can greatly simplify the implementation and improve the behavior of overlays and floating UI elements in a React application.
<h3>State the main difference between useEffect and useLayoutEffect</h3>
<strong>useEffect</strong> and <strong>useLayoutEffect</strong> are both hooks in React that allow you to perform side effects in function components. However, they differ primarily in the timing of their execution in relation to rendering:
<ul>
 	<li><strong>useEffect:</strong>
<ul>
 	<li>It runs asynchronously and after the browser has painted the updated screen.</li>
 	<li>Typically used for most side effects, such as data fetching, setting up subscriptions, etc.</li>
 	<li>Doesn't block the browser from updating the screen.</li>
</ul>
</li>
 	<li><strong>useLayoutEffect:</strong>
<ul>
 	<li>It runs synchronously after all DOM mutations but before the screen is updated or painted.</li>
 	<li>Useful when you need to make DOM measurements or updates and want to ensure they occur before the screen is repainted, preventing flickers.</li>
 	<li>Should be used sparingly as it can block the render process.</li>
</ul>
</li>
</ul>
In most scenarios, <code>useEffect</code> is sufficient and should be preferred due to its non-blocking nature. <code>useLayoutEffect</code> is used for more specific cases where the effect must be synchronized with the layout phase.
<h3>Where do you usually fetch data in React?</h3>
In React, data fetching commonly occurs in the <strong>component lifecycle methods</strong> (for class components) or within the <strong>effect hooks</strong> (for functional components). Here's how it's typically done in each approach:
<ul>
 	<li><strong>Class Components:</strong>
<ul>
 	<li>The <code>componentDidMount</code> lifecycle method is a popular place to fetch data as it ensures that the component is fully mounted in the DOM before making the request.
<pre><code>
class DataComponent extends React.Component {
  componentDidMount() {
    fetch('/api/data')
      .then(response =&gt; response.json())
      .then(data =&gt; this.setState({ data }));
  }
  // ... rest of the component
}
</code></pre>
</li>
</ul>
</li>
 	<li><strong>Functional Components:</strong>
<ul>
 	<li>The <code>useEffect</code> hook is used for side effects, including data fetching, in functional components. To fetch data when the component mounts, you'd use <code>useEffect</code> with an empty dependency array.
<pre><code>
function DataComponent() {
  const [data, setData] = useState(null);

  useEffect(() =&gt; {
    fetch('/api/data')
      .then(response =&gt; response.json())
      .then(fetchedData =&gt; setData(fetchedData));
  }, []);  // Empty dependency array means this effect runs once after component mounts

  // ... rest of the component
}
</code></pre>
</li>
</ul>
</li>
</ul>
Regardless of the approach, it's essential to handle loading states, errors, and potential side effects efficiently for a seamless user experience. Libraries like <strong>react-query</strong> and <strong>SWR</strong> can abstract and optimize many of these concerns, simplifying data-fetching patterns in React applications.
<h3>What are hooks in React?</h3>
In React, <strong>Hooks</strong> are functions that allow you to "hook into" React state and lifecycle features directly from function components. They were introduced in React 16.8 and enable developers to use state and other React features without having to write class components.
<ul>
 	<li><strong>Benefits:</strong>
<ul>
 	<li>Facilitates the creation of cleaner and more readable code.</li>
 	<li>Enables better logic encapsulation and reusability.</li>
 	<li>Reduces the complexity of components by avoiding the "this" keyword and lifecycle methods.</li>
</ul>
</li>
 	<li><strong>Common Hooks:</strong>
<ul>
 	<li><code>useState</code>: Allows you to add state to functional components.
<pre><code>
const [count, setCount] = useState(0);
</code></pre>
</li>
 	<li><code>useEffect</code>: Performs side effects (like data fetching, manual DOM manipulation, etc.) in functional components.
<pre><code>
useEffect(() =&gt; {
  document.title = `Count: ${count}`;
}, [count]);
</code></pre>
</li>
 	<li><code>useContext</code>: Accesses the value from a React context without using a Context Consumer.
<pre><code>
const theme = useContext(ThemeContext);
</code></pre>
</li>
</ul>
</li>
 	<li><strong>Additional Hooks:</strong>
React also offers hooks like <code>useReducer</code>, <code>useCallback</code>, <code>useMemo</code>, <code>useRef</code>, and <code>useLayoutEffect</code>, among others.</li>
 	<li><strong>Custom Hooks:</strong>
You can also create your own hooks, allowing you to extract component logic into reusable functions. Custom hooks are a way to reuse stateful logic, not state itself.</li>
</ul>
Overall, hooks provide a more intuitive way to use React's features within function components, promoting cleaner and more maintainable code.
<h3>If you wanted a component to perform an action only once when the component initially rendered how would you achieve it with a function component?</h3>
To ensure a function component performs an action only once upon its initial render, you would utilize the <strong>useEffect</strong> hook with an empty dependency array. This ensures that the effect runs only once, similar to the <code>componentDidMount</code> lifecycle method in class components.
<pre><code>
import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() =&gt; {
    // Action to be performed only on the initial render
    console.log('Component did mount!');

  }, []);  // Empty dependency array ensures this runs once after component mounts

  return (
    &lt;div&gt;
      My Component Content
    &lt;/div&gt;
  );
}
</code></pre>
By using an empty dependency array in <code>useEffect</code>, the effect does not re-run after the initial execution since no state or prop values are being watched for changes. This is a common pattern for actions that should only occur once, such as initial data fetching or setting up event listeners.
<h3>What is prop-drilling, and how can you avoid it?</h3>
<strong>Prop-drilling</strong>, also known as "prop-threading", refers to the process of passing data through multiple layers of components (from parent to descendant) via props, even if some intermediary components don't need the data themselves. This can lead to code that is hard to maintain and trace, especially in deep component hierarchies.
<pre><code>
function ParentComponent(props) {
  return &lt;ChildComponent someProp={props.someProp} /&gt;;
}

function ChildComponent(props) {
  return &lt;GrandchildComponent someProp={props.someProp} /&gt;;
}

function GrandchildComponent(props) {
  return &lt;div&gt;{props.someProp}&lt;/div&gt;;
}
</code></pre>
Here, even though only <code>GrandchildComponent</code> needs <code>someProp</code>, it's being passed through each layer of the hierarchy.

<strong>Ways to avoid prop-drilling:</strong>
<ul>
 	<li><strong>Context API:</strong> Use React's built-in Context API to provide data to components further down the tree.
<pre><code>
const SomeContext = React.createContext();

function ParentComponent(props) {
  return (
    &lt;SomeContext.Provider value={props.someProp}&gt;
      &lt;ChildComponent /&gt;
    &lt;/SomeContext.Provider&gt;
  );
}

function GrandchildComponent() {
  const someProp = React.useContext(SomeContext);
  return &lt;div&gt;{someProp}&lt;/div&gt;;
}
</code></pre>
</li>
 	<li><strong>Component Composition:</strong> Break down complex components and use component composition to avoid passing unnecessary props.</li>
 	<li><strong>Redux or other state management libraries:</strong> For larger applications, use state management solutions to manage and distribute your application's state without prop-drilling.</li>
</ul>
By using these strategies, you can maintain cleaner, more readable, and more efficient React codebases that are less prone to bugs and easier to refactor.
<h3>How can you reset a component’s state to its initial state?</h3>
To reset a component's state to its initial state in React, there are several methods you can employ:
<ul>
 	<li><strong>Using a Reference:</strong> Store the initial state in a reference and reset the state using that reference.
<pre><code>
import React, { useState, useRef } from 'react';

function MyComponent() {
  const initialState = { count: 0 };
  const [state, setState] = useState(initialState);
  const stateRef = useRef(initialState);

  const resetState = () =&gt; {
    setState(stateRef.current);
  };

  return (
    &lt;div&gt;
      Count: {state.count}
      &lt;button onClick={() =&gt; setState({ count: state.count + 1 })}&gt;Increment&lt;/button&gt;
      &lt;button onClick={resetState}&gt;Reset&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
</li>
 	<li><strong>Using a Function with useState:</strong> useState can accept a function to provide an initial state. If you encapsulate the initial state logic in a function, you can call it both for setting the initial state and resetting it.
<pre><code>
function MyComponent() {
  const createInitialState = () =&gt; ({ count: 0 });
  const [state, setState] = useState(createInitialState);

  const resetState = () =&gt; {
    setState(createInitialState());
  };

  return (
    &lt;div&gt;
      Count: {state.count}
      &lt;button onClick={() =&gt; setState({ count: state.count + 1 })}&gt;Increment&lt;/button&gt;
      &lt;button onClick={resetState}&gt;Reset&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
</li>
</ul>
Both approaches are valid and can be used based on the specific use case and developer preference. The key is to maintain the initial state's representation and use it when you want to revert back to it.
<h3>Explain the difference between useState and useEffect.</h3>
<strong>useState</strong> and <strong>useEffect</strong> are both hooks introduced in React 16.8, but they serve very different purposes:
<ul>
 	<li><strong>useState:</strong>This hook allows you to add state to functional components. Before hooks, state could only be used in class components.
<pre><code>
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0); // initial value is 0
  
  return (
    &lt;div&gt;
      {count}
      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
</li>
 	<li><strong>useEffect:</strong>This hook is used to perform side effects (like data fetching, DOM manipulation, setting up event listeners, etc.) in functional components. It can mimic the behavior of various lifecycle methods in class components, such as <code>componentDidMount</code>, <code>componentDidUpdate</code>, and <code>componentWillUnmount</code>.
<pre><code>
import React, { useState, useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() =&gt; {
    fetch('/api/data')
      .then(response =&gt; response.json())
      .then(result =&gt; setData(result));
    // This runs after the component mounts and after every update
  }, []); // The empty array means it will only run once, similar to componentDidMount

  return (
    &lt;div&gt;
      {data}
    &lt;/div&gt;
  );
}
</code></pre>
</li>
</ul>
In essence:
<ul>
 	<li><strong>useState</strong> is for managing local state in functional components.</li>
 	<li><strong>useEffect</strong> is for handling side effects in functional components.</li>
</ul>
While both hooks provide essential functionality for modern React development, they cater to different aspects of component logic and behavior.
<h3>If you have to set a key value in a component, from where would you get that value?</h3>
In React, a <strong>key</strong> is a special attribute you should provide to elements created dynamically from an array or iterable. It helps React identify which items have changed, been added, or been removed, thus ensuring efficient updates and re-renders. When determining a value for the key:
<ul>
 	<li><strong>Unique Identifiers:</strong>Often, the best approach is to use a unique identifier from your data. If the items come from a database, they might have a unique ID.
<pre><code>
const items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  // ...
];

return items.map(item =&gt; &lt;div key={item.id}&gt;{item.name}&lt;/div&gt;);
</code></pre>
</li>
 	<li><strong>Array Index:</strong>If there's no unique identifier, you might consider using the array index. However, this isn't recommended unless you're certain the list doesn't undergo reorder operations (like sort or splice), as it can lead to performance issues and bugs.
<pre><code>
const items = ['Item 1', 'Item 2'];

return items.map((item, index) =&gt; &lt;div key={index}&gt;{item}&lt;/div&gt;);
</code></pre>
</li>
 	<li><strong>Generate Unique IDs:</strong>If you don't have a natural unique identifier, you can use libraries like <strong>shortid</strong> or <strong>uuid</strong> to generate them.</li>
</ul>
Remember, it's crucial that the key is stable across re-renders for optimal performance. It should not be generated randomly for each render, as this would defeat its purpose.
<h3>Explain the concept of lazy loading React components</h3>
<strong>Lazy loading</strong> is a technique in React where components are loaded and rendered only when they're needed (typically when they come into the viewport or upon a particular event) instead of loading them upfront during the initial page load. This strategy can improve the performance and reduce the initial bundle size of your application, leading to faster load times.

React provides a built-in mechanism for lazy loading components using <code>React.lazy()</code> and <code>Suspense</code>.
<ul>
 	<li><strong>React.lazy():</strong>It allows you to render a dynamic import as a regular component. It automatically takes care of loading the component when it’s needed.
<pre><code>
const LazyLoadedComponent = React.lazy(() =&gt; import('./LazyLoadedComponent'));
</code></pre>
</li>
 	<li><strong>Suspense:</strong>Works in conjunction with <code>React.lazy()</code> and provides a fallback UI (like a loading spinner) while the component is being loaded.
<pre><code>
import React, { Suspense } from 'react';

function App() {
  return (
    &lt;div&gt;
      &lt;Suspense fallback=&lt;div&gt;Loading...&lt;/div&gt;&gt;
        &lt;LazyLoadedComponent /&gt;
      &lt;/Suspense&gt;
    &lt;/div&gt;
  );
}
</code></pre>
</li>
</ul>
For scenarios where you'd like to lazy-load components based on the viewport or other conditions, third-party libraries such as <strong>react-loadable</strong> or utilities like <strong>IntersectionObserver</strong> can be leveraged.

In summary, lazy loading React components is a powerful tool for optimizing the performance of your application, ensuring users download only what they need when they need it.
<h3>Explain the main differences between useMemo and useCallback</h3>
<strong>useMemo</strong> and <strong>useCallback</strong> are both React hooks introduced to optimize performance by avoiding unnecessary recalculations and re-renders. While they have similar goals, they're used in different scenarios:
<ul>
 	<li><strong>useMemo:</strong>It returns a <strong>memoized value</strong>. This hook is useful when you have computationally expensive calculations that you don't want to execute on every render. Instead, you want them to recalculate only when specific dependencies change.
<pre><code>
import React, { useMemo } from 'react';

function Component(props) {
  const computedValue = useMemo(() =&gt; {
    // some expensive calculation based on props.data
    return expensiveCalculation(props.data);
  }, [props.data]);

  return &lt;div&gt;{computedValue}&lt;/div&gt;;
}
</code></pre>
</li>
 	<li><strong>useCallback:</strong>It returns a <strong>memoized callback function</strong>. This hook is particularly useful when passing callbacks to performance-sensitive child components (like those wrapped in <code>React.memo</code>). By ensuring that the callback function reference remains consistent across renders (unless dependencies change), we prevent unnecessary re-renders of those child components.
<pre><code>
import React, { useCallback } from 'react';

function ParentComponent() {
  const handleChildClick = useCallback(() =&gt; {
    // handle click logic
  }, []); // Empty dependency array means the callback will not change across re-renders

  return &lt;ChildComponent onClick={handleChildClick} /&gt;;
}
</code></pre>
</li>
</ul>
In essence:
<ul>
 	<li><strong>useMemo</strong> is about memoizing values.</li>
 	<li><strong>useCallback</strong> is about memoizing functions.</li>
</ul>
Both hooks accept a dependency array, and the provided value or function is recalculated/recreated only when values in this array change between renders.
<h3>Why would you ever use forwardRef in React?</h3>
<strong>forwardRef</strong> in React is a tool for forwarding <strong>refs</strong> (references) to a child component. It is particularly useful in situations where you need to access the DOM elements or instance methods of a child component from a parent component. Here are some primary use cases:
<ul>
 	<li><strong>Focus Management:</strong>Often in user interfaces, after certain actions are completed, you might need to set focus on a particular child element for accessibility and usability purposes.</li>
 	<li><strong>Animating Components:</strong>When using libraries like <strong>gsap</strong> or <strong>anime.js</strong>, you might need direct access to the DOM node to perform animations.</li>
 	<li><strong>Integration with Third-party Libraries:</strong>Some external libraries require direct access to DOM nodes, and forwarding refs can be essential in these scenarios.</li>
 	<li><strong>Reusable Components:</strong>If you're building a component library, you might use <strong>forwardRef</strong> to ensure components are extensible and can pass along refs when needed.</li>
</ul>
<pre><code>
import React, { forwardRef } from 'react';

const CustomInput = forwardRef((props, ref) =&gt; {
  return &lt;input ref={ref} {...props} /&gt;;
});

function App() {
  const inputRef = React.useRef(null);

  const handleButtonClick = () =&gt; {
    // Focus the input when the button is clicked
    inputRef.current.focus();
  };

  return (
    &lt;div&gt;
      &lt;CustomInput ref={inputRef} /&gt;
      &lt;button onClick={handleButtonClick}&gt;Focus Input&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
As shown above, <strong>forwardRef</strong> allows the parent component (<code>App</code> in this case) to access the underlying <code>input</code> DOM node of the <code>CustomInput</code> child component.
<h3>At what point does the useEffect cleanup function run?</h3>
The <strong>useEffect</strong> hook in React provides a way to execute side effects (like setting up event listeners, fetching data, or subscribing to external sources) in functional components. Additionally, <strong>useEffect</strong> allows for a <strong>cleanup function</strong> which is used to undo these side effects and prevent potential memory leaks or unwanted behaviors.

The cleanup function of <strong>useEffect</strong> runs:
<ul>
 	<li>Before the component is unmounted from the DOM, ensuring any setup done in the effect is properly cleaned up.</li>
 	<li>Before re-running the effect when one of its dependencies has changed. This ensures that any previous effect is cleaned up before the new effect is run.</li>
</ul>
<pre><code>
import React, { useState, useEffect } from 'react';

function ExampleComponent() {
  const [count, setCount] = useState(0);

  useEffect(() =&gt; {
    // Side effect: Setting up an event listener
    const handleDocumentClick = () =&gt; {
      console.log('Document was clicked!');
    };
    document.addEventListener('click', handleDocumentClick);

    // Cleanup function
    return () =&gt; {
      // Cleaning up the event listener
      document.removeEventListener('click', handleDocumentClick);
    };
  }, [count]); // This effect depends on the 'count' state
}
</code></pre>
In the example above:
<ul>
 	<li>When <code>count</code> changes, before the new effect is executed, the cleanup function will run, removing the previous event listener.</li>
 	<li>If the <code>ExampleComponent</code> is unmounted from the DOM, the cleanup function will also run, ensuring that the event listener is removed and preventing potential memory leaks.</li>
</ul>
In essence, the cleanup function is React's way of ensuring that side effects don't leave behind unwanted behaviors or resources.
<h3>Explain the concept of Reducers and Context in React</h3>
Both <strong>Reducers</strong> and <strong>Context</strong> are powerful concepts in React, often used in tandem to manage global state and pass data throughout components without prop-drilling. Let's dive into each concept separately:
<h4>Reducers</h4>
A <strong>reducer</strong> is a pure function that takes the current state and an action, then returns the next state. It follows the concept of the reducer in functional programming, where it "reduces" a collection to a single value. In the context of React (and state management libraries like Redux), reducers are used to handle state transitions in a predictable manner.
<pre><code>
function counterReducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}
</code></pre>
In this example, the <code>counterReducer</code> adjusts the <code>count</code> based on the provided action type.
<h4>Context</h4>
The <strong>Context</strong> API provides a way to pass data through the component tree without having to pass props down manually at every level. It is designed to share data that can be considered "global", such as themes, user authentication, or other shared utilities.
<pre><code>
import React, { createContext, useContext } from 'react';

// Create a Context
const ThemeContext = createContext();

function App() {
  return (
    &lt;ThemeContext.Provider value="dark"&gt;
      &lt;ChildComponent /&gt;
    &lt;/ThemeContext.Provider&gt;
  );
}

function ChildComponent() {
  // Use the Context value
  const theme = useContext(ThemeContext);
  return &lt;div&gt;Current theme is: {theme}&lt;/div&gt;
}
</code></pre>
In the example, the <code>ChildComponent</code> can access the theme value without receiving it as a direct prop, thanks to the Context API.

<strong>Together:</strong> These two concepts can be combined using the <code>useReducer</code> hook and the Context API to create a global state management solution. The reducer handles state logic and transitions, while the Context API distributes the state and functions to manipulate it throughout the component tree.
<h3>How would you catch render errors in React components at the global scope?</h3>
To catch render errors in React components at the global scope, you would use a feature called <strong>Error Boundaries</strong>. An error boundary is a React component that catches JavaScript errors anywhere in their child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed.
<h4>Creating an Error Boundary</h4>
You can define an error boundary by creating a new component with the static method <strong>getDerivedStateFromError()</strong> and/or the instance method <strong>componentDidCatch()</strong>.
<pre><code>
import React, { Component } from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can log the error to an error reporting service here
    console.error(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI here
      return &lt;h1&gt;Something went wrong.&lt;/h1&gt;;
    }
    return this.props.children;
  }
}
</code></pre>
<h4>Using the Error Boundary</h4>
Once you have an error boundary defined, you can wrap your entire application (or parts of it) inside this boundary.
<pre><code>
function App() {
  return (
    &lt;ErrorBoundary&gt;
      &lt;MainComponent /&gt;
    &lt;/ErrorBoundary&gt;
  );
}
</code></pre>
If any error occurs inside <code>MainComponent</code> or any of its children, the error boundary will catch it and display the fallback UI, ensuring that the entire application doesn't crash due to a single component's failure.

Note: Error boundaries only catch errors in the components below them in the tree, not within themselves. Therefore, it's a good practice to place them at a high level in your component hierarchy, or around critical sections of your app.
<h3>How does useEffect check changes in its array dependency?</h3>
The <strong>useEffect</strong> hook in React triggers side-effects in function components. One of its features is the dependency array, which you can provide to ensure that the effect runs only when the specified dependencies have changed between renders.

<strong>useEffect</strong> determines whether to re-run its effect based on a shallow comparison of the values inside the dependency array from the previous render to the current render.
<h4>Shallow Comparison</h4>
A shallow comparison checks if the values at corresponding indexes of the dependency array are the same between consecutive renders. It does not dive into nested objects or arrays, but checks only the top-level references. Here's a breakdown:
<ul>
 	<li><strong>Primitives:</strong> For primitive values (like numbers, strings, or booleans), it checks if they are the same.</li>
 	<li><strong>Objects and Arrays:</strong> For objects and arrays, it checks the reference, not the content. If you create a new object or array every render, even with the same content, it will cause the effect to run every time.</li>
</ul>
<pre><code>
const [count, setCount] = React.useState(0);

// This effect will run on every render, 
// because a new array is created every time
useEffect(() =&gt; {
  console.log('This will run every render');
}, [count, []]);

// This effect will run only when 'count' changes, 
// as the dependency array contains only primitive values
useEffect(() =&gt; {
  console.log('This will run when count changes');
}, [count]);
</code></pre>
It's crucial to ensure that objects or arrays passed to the dependency array have stable identities across renders, especially if their contents aren't changing. Otherwise, it could lead to unnecessary effect runs. Using state setters, useMemo, or useCallback can help maintain stable object or function references across renders.


[original article](https://montedelgallo.com/get-ready-for-your-next-react-job-interview/)