Skip to content

Commit da5c520

Browse files
committed
Add useMemo hook questions
1 parent 12655d8 commit da5c520

File tree

1 file changed

+207
-4
lines changed

1 file changed

+207
-4
lines changed

README.md

Lines changed: 207 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5389,8 +5389,8 @@ class ParentComponent extends React.Component {
53895389
53905390
241. ### What is the difference between useState and useRef hook?
53915391
1. useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes.
5392-
Essentially, useRef is like a “box” that can hold a mutable value in its (.current) property.
5393-
2. useState allows us to update the state inside components. While useRef allows referencing DOM elements.
5392+
Essentially, useRef is like a “box” that can hold a mutable value in its (`.current`) property.
5393+
2. useState allows us to update the state inside components. While useRef allows referencing DOM elements and tracking values.
53945394
53955395
**[⬆ Back to Top](#table-of-contents)**
53965396
@@ -6279,7 +6279,7 @@ Technically it is possible to write nested function components but it is not sug
62796279
{ id: 5, name: 'Eden' }
62806280
];
62816281

6282-
export default function UserSearch() {
6282+
export default function UserSearch({ users }) {
62836283
const [searchTerm, setSearchTerm] = useState('');
62846284
const [counter, setCounter] = useState(0);
62856285

@@ -6843,6 +6843,7 @@ Technically it is possible to write nested function components but it is not sug
68436843
In this case, a change in `theme` will also trigger a re-render in components that only care about `user`.
68446844
68456845
This issue can be fixed in two ways,
6846+
68466847
**1. Split Contexts**
68476848
Create separate contexts for unrelated pieces of state:
68486849
@@ -6864,7 +6865,7 @@ Technically it is possible to write nested function components but it is not sug
68646865
68656866
286. ### What would the context value be for no matching provider?
68666867
6867-
When a component calls `useContext(SomeContext)` but **no matching** `**<SomeContext.Provider>**` **is present higher up in the component tree**, the **default value** passed to `React.createContext(defaultValue)` is returned.
6868+
When a component calls `useContext(SomeContext)` but **no matching** `<SomeContext.Provider>` **is present higher up in the component tree**, the **default value** passed to `React.createContext(defaultValue)` is returned.
68686869
68696870
```js
68706871
const ThemeContext = React.createContext('light'); // 'light' is the default value
@@ -7082,6 +7083,208 @@ Technically it is possible to write nested function components but it is not sug
70827083
This issue can be avoided by batching your DOM reads and writes and prevent unnecessary reads after writes.
70837084
70847085
**[⬆ Back to Top](#table-of-contents)**
7086+
7087+
295. ### How Do You Use useRef to Access a DOM Element in React? Give an example.
7088+
The `useRef` hook is commonly used in React to directly reference and interact with DOM elements — like focusing an input, scrolling to a section, or controlling media elements.
7089+
7090+
When you assign a ref to a DOM element using useRef, React gives you access to the underlying DOM node via the .current property of the ref object.
7091+
7092+
**Example: Focus an input**
7093+
7094+
```js
7095+
import React, { useRef } from 'react';
7096+
7097+
function FocusInput() {
7098+
const inputRef = useRef(null); // create the ref
7099+
7100+
const handleFocus = () => {
7101+
inputRef.current.focus(); // access DOM element and focus it
7102+
};
7103+
7104+
return (
7105+
<div>
7106+
<input type="text" ref={inputRef} />
7107+
<button onClick={handleFocus}>Focus the input</button>
7108+
</div>
7109+
);
7110+
}
7111+
```
7112+
**Note:** The DOM reference is only available **after the component has mounted** — typically accessed in `useEffect` or event handlers.
7113+
7114+
**[⬆ Back to Top](#table-of-contents)**
7115+
7116+
296. ### Can you use useRef to persist values across renders??
7117+
Yes, you can use `useRef` to persist values across renders in React. Unlike `useState`, changing `.current` does not cause re-renders, but the value is preserved across renders.
7118+
7119+
**Example:**
7120+
```js
7121+
function Timer() {
7122+
const renderCount = useRef(0);
7123+
useEffect(() => {
7124+
renderCount.current++;
7125+
console.log("Render count:", renderCount.current);
7126+
});
7127+
7128+
return <div>Check console for render count.</div>;
7129+
}
7130+
```
7131+
**[⬆ Back to Top](#table-of-contents)**
7132+
7133+
297. ### Can useRef be used to store previous values?
7134+
Yes, `useRef` is a common pattern when you want to compare current and previous props or state without causing re-renders.
7135+
7136+
**Example: Storing previous state value**
7137+
```js
7138+
import { useEffect, useRef, useState } from 'react';
7139+
7140+
function PreviousValueExample() {
7141+
const [count, setCount] = useState(0);
7142+
const prevCountRef = useRef();
7143+
7144+
useEffect(() => {
7145+
prevCountRef.current = count;
7146+
}, [count]);
7147+
7148+
const prevCount = prevCountRef.current;
7149+
7150+
return (
7151+
<div>
7152+
<p>Current: {count}</p>
7153+
<p>Previous: {prevCount}</p>
7154+
<button onClick={() => setCount(c => c + 1)}>Increment</button>
7155+
</div>
7156+
);
7157+
}
7158+
```
7159+
7160+
**[⬆ Back to Top](#table-of-contents)**
7161+
7162+
298. ### Is it possible to access a ref in the render method?
7163+
Yes, you can access a ref in the render method, but what you get from it depends on how you're using the ref and when in the component lifecycle you're rendering.
7164+
7165+
For example, when using ref to access a DOM node (e.g., divRef.current), it's not immediately available on the first render.
7166+
```js
7167+
const divRef = useRef(null);
7168+
7169+
console.log(divRef.current); // ❌ null on initial render
7170+
return <div ref={divRef}>Hello</div>;
7171+
```
7172+
7173+
**[⬆ Back to Top](#table-of-contents)**
7174+
7175+
299. ### What are the common usecases of useRef hook?
7176+
Some of the common cases are:
7177+
* Automatically focus an input when a component mounts.
7178+
* Scroll to a specific element.
7179+
* Measure element dimensions (`offsetWidth`, `clientHeight`).
7180+
* Control video/audio playback.
7181+
* Integrate with non-React libraries (like D3 or jQuery).
7182+
7183+
**[⬆ Back to Top](#table-of-contents)**
7184+
7185+
300. ### What is useImperativeHandle Hook? Give an example.
7186+
`useImperativeHandle` is a React Hook that allows a **child component** to expose **custom functions or properties** to its **parent component**, when using `ref`.
7187+
It is typically used with `forwardRef` and is very useful in cases like **modals**, **dialogs**, **custom inputs**, etc., where the parent needs to **control behavior imperatively** (e.g., open, close, reset).
7188+
7189+
**Example: Dialog component**
7190+
```js
7191+
import React, {
7192+
useRef,
7193+
useState,
7194+
useImperativeHandle,
7195+
forwardRef,
7196+
} from 'react';
7197+
import './Dialog.css';
7198+
7199+
const Dialog = forwardRef((props, ref) => {
7200+
const [isOpen, setIsOpen] = useState(false);
7201+
const [formData, setFormData] = useState('');
7202+
7203+
useImperativeHandle(ref, () => ({
7204+
open: () => setIsOpen(true),
7205+
close: () => setIsOpen(false),
7206+
reset: () => setFormData(''),
7207+
}));
7208+
7209+
if (!isOpen) return null;
7210+
7211+
return (
7212+
<div className="dialog">
7213+
<h2>Dialog</h2>
7214+
<input
7215+
type="text"
7216+
value={formData}
7217+
placeholder="Type something..."
7218+
onChange={(e) => setFormData(e.target.value)}
7219+
/>
7220+
<br />
7221+
<button onClick={() => setIsOpen(false)}>Close</button>
7222+
</div>
7223+
);
7224+
});
7225+
7226+
function Parent() {
7227+
const dialogRef = useRef();
7228+
7229+
return (
7230+
<div>
7231+
<h1>useImperativeHandle Dialog Example</h1>
7232+
<button onClick={() => dialogRef.current.open()}>Open Dialog</button>
7233+
<button onClick={() => dialogRef.current.reset()}>Reset Dialog</button>
7234+
<button onClick={() => dialogRef.current.close()}>Close Dialog</button>
7235+
7236+
<Dialog ref={dialogRef} />
7237+
</div>
7238+
);
7239+
}
7240+
7241+
export default Parent;
7242+
```
7243+
7244+
**[⬆ Back to Top](#table-of-contents)**
7245+
7246+
301. ### When should you use useImperativeHandle?
7247+
The useImperativeHandler hook will be used in below cases:
7248+
7249+
* You want to expose **imperative methods** from a child component
7250+
- Custom input controls exposing `focus`, `clear`, or `validate` methods
7251+
- Modal components exposing `open()` and `close()` methods
7252+
- Scroll containers exposing `scrollToTop()` or `scrollToBottom()` methods
7253+
* You want to **hide internal implementation** but provide controlled external access.
7254+
* You're building **reusable component libraries** (e.g., inputs, modals, form controls).
7255+
7256+
**[⬆ Back to Top](#table-of-contents)**
7257+
7258+
302. ### Is that possible to use useImperativeHandle without forwardRef?
7259+
**No.** `useImperativeHandle` only works when the component is wrapped in `forwardRef`. It's the combination that allows parent components to use a `ref` on a function component.
7260+
7261+
**[⬆ Back to Top](#table-of-contents)**
7262+
7263+
303. ### How is useMemo different from useCallback?
7264+
The following table compares both useMemo and useCallback:
7265+
7266+
| Feature | `useMemo` | `useCallback` |
7267+
| --- | --- | --- |
7268+
| **Purpose** | Memoizes the **result of a computation** | Memoizes a **function reference** |
7269+
| **Returns** | A **value** (e.g., result of a function) | A **function** |
7270+
| **Usage** | `useMemo(() => computeValue(), [deps])` | `useCallback(() => doSomething(), [deps])` |
7271+
| **Primary Use Case** | Avoid expensive recalculations | Prevent unnecessary re-creations of functions |
7272+
| **Common Scenario** | Filtering, sorting, calculating derived data | Passing callbacks to child components |
7273+
| **When It's Useful** | When the value is expensive to compute | When referential equality matters (e.g., props) |
7274+
| **Recomputed When** | Dependencies change | Dependencies change |
7275+
| **Returned Value Type** | Any (number, object, array, etc.) | Always a function |
7276+
| **Overhead** | Slight (evaluates a function and caches result) | Slight (caches a function reference) |
7277+
7278+
**[⬆ Back to Top](#table-of-contents)**
7279+
7280+
304. ### Does useMemo prevent re-rendering of child components?
7281+
7282+
The `useMemo` hook **does not directly prevent re-rendering of child components**. Its main purpose is to memoize the result of an expensive computation so that it doesn’t get recalculated unless its dependencies change. While this can improve performance, it doesn’t inherently control whether a child component re-renders.
7283+
7284+
However, `useMemo` **can help prevent re-renders** when the memoized value is passed as a prop to a child component that is wrapped in `React.memo`. In that case, if the memoized value doesn’t change between renders (i.e., it has the same reference), React.memo can skip re-rendering the child. So, while `useMemo` doesn’t stop renders on its own, it **works in combination** with tools like `React.memo` to optimize rendering behavior.
7285+
7286+
**[⬆ Back to Top](#table-of-contents)**
7287+
70857288
## Old Q&A
70867289
70877290
1. ### Why should we not update the state directly?

0 commit comments

Comments
 (0)