An uncontrolled form lets the DOM manage input state while React reads it when an action requires the value. A ref provides access without re-rendering on every keystroke. section 5.0 section 5.3.2
WeekPicker date entry
A WeekPicker attaches textboxRef to a text input. The browser displays typed characters, but goToDate reads textboxRef.current.value only when the user clicks Go, then dispatches SET_DATE. section 5.3.2
Use this pattern when:
- The component does not need to respond to every keystroke. section 5.3.2
- A ref can read or update the DOM element through its current property. section 5.4
- Prefer controlled components when React should remain the single source of truth. section 5.4
Listing 5.4 The WeekPicker with a text box and Go button
import {useReducer, useRef} from "react";
import reducer from "./weekReducer";
import {getWeek} from "../../utils/date-wrangler";
import {
FaChevronLeft,
FaCalendarDay,
FaChevronRight,
FaCalendarCheck
} from "react-icons/fa";
export default function WeekPicker ({date}) {
const [week, dispatch] = useReducer(reducer, date, getWeek);
const textboxRef = useRef(); #1
function goToDate () { #2
dispatch({ #3
type: "SET_DATE", #3
payload: textboxRef.current.value #4
});
}
return (
<div>
<p className="date-picker">
// Prev button
// Today button
<span>
<input
type="text"
ref={textboxRef} #5
placeholder="e.g. 2020-09-02"
defaultValue="2020-06-24"
/>
<button #6
className="go btn"
onClick={goToDate} #7
>
<FaCalendarCheck/>
<span>Go</span>
</button>
</span>
// Next button
</p>
<p>
{week.start.toDateString()} - {week.end.toDateString()}
</p>
</div>
);
}
#1 Create a ref to hold the reference to the text box.
#2 Define a handler for the Go button.
#3 Dispatch the SET_DATE action.
#4 Use the ref to get the text value in the text box.
#5 Add a text box with a ref attribute to the UI.
#6 Add the Go button to the UI.
#7 Assign the handler to set the date.
Inspect the WeekPicker implementation showing the ref, input binding, and dispatch handler. section 5.3.2

