CodeBlanks Logo Icon CodeBlanks

Summary - useRef

Write a form that focuses an input automatically when a button is pressed.

Summary - useRef

In this group you saw what useRef is, how it differs from state, how it's used to access DOM elements, and how it's useful to store a timer id.

Two main uses: bind to a DOM element with ref={ '{ inputRef }' } and silently store a value with ref.current = .... Neither triggers a render.

In the next step you'll write a checkbox component that combines DOM access and value storage.

Practice Checkbox component

Complete the skeleton. Write a Checkbox component. Create inputRef = useRef(null). Keep a checked state. Show <input type="checkbox" ref={ '{ inputRef }' } checked={ '{ checked }' } onChange={ '{ ... }' } />; on change, call setChecked(c => !c). Add a <label>Accept</label>. Export it.

Starter code

App.jsx
import { useRef, useState } from "react";

// Write the Checkbox component here

Sample solution

App.jsx
import { useRef, useState } from "react";

function Checkbox() {
  const inputRef = useRef(null);
  const [checked, setChecked] = useState(false);
  return (
    <div>
      <input type="checkbox" ref={inputRef} checked={checked} onChange={() => setChecked((c) => !c)} />
      <label>Accept</label>
    </div>
  );
}

export default Checkbox;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What's the difference between useRef and setState?

  • useRef only holds numbers
  • useRef doesn't trigger render Correct answer
  • setState can't be used
  • useRef is faster

Explanation: useRef doesn't trigger render.

2 Match the useRef steps

Term Meaning
useRef(null) Initial value
ref={inputRef} Binding
current Access
clearInterval Cleanup

All lessons in Beginner