DEV Community

LAKSHMI G
LAKSHMI G

Posted on

React Question & Answer

7)What is the difference between useRef and useState? When would you choose one over the other?
useState

  • To store data that affects the UI and needs re-rendering when changed.
  • When the value changes, the component re-renders automatically.
  • Value is updated using the setter function (e.g., setCount).
  • Commonly used for dynamic UI data (like inputs, counters, etc.).

useRef

  • Used to store data that does not cause re-render when changed.
  • - When the value changes, the component does not re-render.Value is updated using the .current property (e.g., ref.current).
  • - Commonly used for DOM access, timers, or storing previous values.
Use useState → when you want the UI to update.
Use useRef → when you just want to keep a value without re-rendering.

**When to Use Each:**

- Use useState → when you need to update the UI based on changing data (e.g., form input, counter, API data).
- Use useRef → when you need to store values that persist across renders but shouldn’t trigger re-render,like
Previous values

DOM element references

Timers or intervals


Enter fullscreen mode Exit fullscreen mode

- Example:


import React, { useState, useRef } from "react";

function Example() {
  const [count, setCount] = useState(0); // triggers re-render when updated
  const ref = useRef(0); // does not trigger re-render

  const handleClick = () => {
    setCount(count + 1); // re-renders component
    ref.current += 1; // value updates but no re-render
    console.log("Ref Value:", ref.current);
  };

  return (
    <div>
      <h2>Count (state): {count}</h2>
      <h3>Ref (no re-render): {ref.current}</h3>
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
}

export default Example;
Enter fullscreen mode Exit fullscreen mode

8)How can you use useRef to focus an input field when a button is clicked?

  • If i can use the useRef hook to directly access an input element in React.
  • By attaching the ref to the input and calling ref.current.focus() inside a button click handler, I can focus the input field programmatically.

Example:

import React, { useRef } from "react";

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

  const handleFocus = () => {
    inputRef.current.focus(); // focus the input field
  };

  return (
    <div>
      <h2>Focus Input Example</h2>
      <input ref={inputRef} type="text" placeholder="Click the button to focus" />
      <button onClick={handleFocus}>Focus Input</button>
    </div>
  );
}

export default FocusInput;
Enter fullscreen mode Exit fullscreen mode

9)Does changing the value of a useRef variable cause re-render? Why?

  • No, changing the value of a useRef variable does not trigger a re-render because React does not monitor refs for rendering updates.
  • Refs are used for storing mutable data **or accessing DOM elements, not for managing UI state**

Example:

import React, { useRef, useState } from "react";

function Example() {
  const [count, setCount] = useState(0);
  const ref = useRef(0);

  const handleClick = () => {
    ref.current += 1; // changes value but doesn't re-render
    console.log("Ref Value:", ref.current);
  };

  return (
    <div>
      <h2>Count (State): {count}</h2>
      <h3>Ref Value: {ref.current}</h3>
      <button onClick={() => setCount(count + 1)}>Update State</button>
      <button onClick={handleClick}>Update Ref</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

10)How would you use useRef to store the previous render’s value of a state?

I can store the previous render’s state value using the useRef hook.
I update the ref inside a useEffect, so it keeps the last state value without causing re-renders.
This technique helps compare the current and previous values efficiently.
Example:

import React, { useState, useEffect, useRef } from "react";

function PreviousValueExample() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef(); // to store previous value

  useEffect(() => {
    prevCountRef.current = count; // store current count before next render
  }, [count]); // runs every time count changes

  const prevCount = prevCountRef.current;

  return (
    <div>
      <h2>Current Count: {count}</h2>
      <h3>Previous Count: {prevCount}</h3>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

export default PreviousValueExample;
Enter fullscreen mode Exit fullscreen mode

`
11)You have a counter that should increase by 2 each time a button is clicked. Why does the following not work? How would you fix it?

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

const handleClick = () => {
  setCount(count + 1);
  setCount(count + 1);
};
Enter fullscreen mode Exit fullscreen mode

Why does the following not work

The counter didn’t increase by 2 because React batches state updates, and both updates used the old value of count


setCount(count + 1)//0+1=1 result is not 2 ans is 1
setCount(count + 1)//also uses 0 → sets it to 1 again

Here count is 0

Correct Way how to (Fix):

  • Use the functional form of setState, which gives you the latest value of state:


const handleClick = () => {
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
};

setCount => prevCount is 0, sets to 1 // 0+1=1

setCount => prevCount is now 1, sets to 2 //1+1=2

Here 1 is the previous value 0+1=1

12)What is the difference between using useEffect with:

no dependency array []

empty dependency array []

specific dependency [count]
Enter fullscreen mode Exit fullscreen mode

no dependency array []


useEffect(() => {
console.log("Effect runs");
});

No array: runs after every render use case Rare, runs always.
empty dependency array []


useEffect(() => {
console.log("Effect runs once");
}, []);

Only once (on mount) is this use case Initialization logic like
- Fetching data from API
- Subscribing to events
- Setting up timers

specific dependency [count]


useEffect(() => {
console.log("Effect runs when count changes");
}, [count]);

Specific dependency [count]: runs after the first render and whenever count changes.
In this use Case are State-dependent logic or props

Top comments (0)