MediumConcept

What is the difference between useRef and useState in React?

Technology:
React
Experience:
Mid-level,
Senior

Quick answer

Updating state triggers a re-render, while changing a ref's .current value does not; use state for data shown on screen and refs for DOM access or values that must persist without causing renders.

Detailed explanation

useRef returns a mutable object whose .current property lives for the whole life of the component. Typical uses are holding a DOM node (to focus an input or measure an element), storing a timer ID, or remembering the previous value of a prop.

Because React does not know when you change a ref, the UI will not update. If a value affects what the user sees, it belongs in state. Avoid reading or writing ref.current during rendering, except for lazy initialisation.

Example

jsx
function SearchBox() {
  const inputRef = useRef(null);
  const [query, setQuery] = useState("");   // changes the UI

  return (
    <>
      <input ref={inputRef} value={query} onChange={e => setQuery(e.target.value)} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </>
  );
}
  • ReactEasy

    What are React hooks and what are the rules of hooks?

    Hooks are functions such as useState and useEffect that let function components use state, lifecycle behaviour and other React features; they must be called at the top level of a component or custom hook, never inside loops, conditions or nested functions.

    Junior 路 Mid-level 路 React Hooks
  • ReactMedium

    How does useEffect work in React and what is the dependency array?

    useEffect runs a function after the component renders; the dependency array tells React when to re-run it: with no array it runs after every render, with an empty array only after the first, and with values only when those values change.

    Junior 路 Mid-level 路 React Hooks
  • ReactMedium

    What is prop drilling and how do you avoid it in React?

    Prop drilling is passing props through several layers of components that do not use them just to reach a deeply nested child; you avoid it with composition, the Context API or a state management library.

    Junior 路 Mid-level 路 State Management
  • ReactEasy

    What is the difference between props and state in React?

    Props are read-only inputs passed from a parent component, while state is data a component owns and can change over time, which triggers a re-render when updated.

    Intern 路 Junior 路 State Management