React useRef & useMemo

Access DOM nodes and cache calculations.

✍️ 3 exercises + code challenge in this lesson

useRef

const inputRef = useRef(null); attach it with ref={inputRef}, then use inputRef.current to reach the DOM element (e.g. to focus it). A ref can also store a value that does not trigger re-renders.

useMemo

useMemo(() => expensiveCalc(a), [a]) remembers a calculated value and only recalculates when its dependencies change.

Key Takeaways: React useRef & useMemo

Mastering React useRef & useMemo helps you write clean and reliable React code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

React useRef & useMemo Code Example

React
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.25.6/babel.min.js"></script>

<script type="text/babel">
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
function App() {
  const inputRef = useRef(null);
  const renders = useRef(0);
  const [query, setQuery] = useState("");
  const [, force] = useState(0);
  renders.current++;

  const words = ["react", "redux", "router", "python", "pandas", "sql", "svelte"];
  const results = useMemo(
    () => words.filter(w => w.includes(query.toLowerCase())),
    [query]
  );

  return (
    <div>
      <input ref={inputRef} value={query} onChange={e => setQuery(e.target.value)} placeholder="Search..." />{" "}
      <button onClick={() => inputRef.current.focus()}>Focus input</button>{" "}
      <button onClick={() => force(n => n + 1)}>Re-render</button>
      <p>{results.join(", ") || "No matches"}</p>
      <small>Rendered {renders.current} times</small>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
Free sign-in required · Google login available

React useRef & useMemo Practice Exercises

Check what you learned in “React useRef & useMemo”.

/ 3 solved
Fill in the blank

Create a ref.

const inputRef = (null);
✓ Correct! Not quite. Try again.
Multiple choice

Does changing ref.current cause a re-render?

✓ Correct! Not quite. Try again.
Code challenge

Attach a ref to the input and focus it in a useEffect when the component mounts.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services