useInput Hook

EasyReact Hooks15 min5 tests

Build a reusable useInput custom hook that manages controlled text-input state, exposing the current value, an onChange handler, and a reset function.

Custom hooks are the standard way to package and reuse stateful logic in React. A very common piece of reusable logic is managing the state of a controlled form input: holding the current value, updating it on every keystroke, and resetting it back to a known starting point.

In this exercise you'll implement useInput(initial = ""). The hook returns an object with three members:

  • value — the current string value (starts at initial).
  • onChange — an event handler suitable for an input's onChange prop. It reads event.target.value and updates the stored value.
  • reset — a function that sets the value back to initial.

Wire the hook into a small App that renders:

  • A controlled text input with placeholder "Type here", bound to value and onChange.
  • A Reset button that calls reset.
  • A live region (role="status") that echoes You typed: {value}.

Typing should update both the input and the status text. Clicking Reset should clear everything back to the initial value. The whole point of the hook is that the App component stays tiny while all the input logic lives in useInput.

Requirements

  • Implement a custom hook useInput(initial = "") inside App.tsx that returns { value, onChange, reset }.
  • value must start at initial and be a string.
  • onChange must accept a change event and update value from event.target.value.
  • reset must restore value to the original initial value.
  • Render a controlled text input with placeholder "Type here" bound to the hook's value and onChange.
  • Render a real <button> labeled "Reset" that calls the hook's reset.
  • Render an element with role="status" showing exactly You typed: {value} that updates live.
Hints (5)
  1. Use useState(initial) inside the hook to hold the value. The hook is just a function that calls React hooks and returns an object.
  2. onChange should be (e) => setValue(e.target.value). The input passes the native event, so read e.target.value.
  3. reset should call setValue(initial) — capture initial from the hook's parameter so reset always returns to the original starting value.
  4. In App, spread or pass the returned members explicitly: value={value} and onChange={onChange} on the input, and onClick={reset} on the button.
  5. The status text is just You typed: followed by the current value — render {You typed: ${value}} (or the two pieces) inside the role="status" element so it re-renders on every change.

Topics

  • React
  • React Hooks

Asked at

Atlassian · Delhivery · CRED · BrowserStack · Groww · Amazon

Join Us
blur