useInput Hook
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 atinitial).onChange— an event handler suitable for an input'sonChangeprop. It readsevent.target.valueand updates the stored value.reset— a function that sets the value back toinitial.
Wire the hook into a small App that renders:
- A controlled text input with placeholder
"Type here", bound tovalueandonChange. - A
Resetbutton that callsreset. - A live region (
role="status") that echoesYou 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 }. valuemust start atinitialand be a string.onChangemust accept a change event and updatevaluefromevent.target.value.resetmust restorevalueto the originalinitialvalue.- 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'sreset. - Render an element with
role="status"showing exactlyYou typed: {value}that updates live.
Hints (5)
- Use
useState(initial)inside the hook to hold the value. The hook is just a function that calls React hooks and returns an object. onChangeshould be(e) => setValue(e.target.value). The input passes the native event, so reade.target.value.resetshould callsetValue(initial)— captureinitialfrom the hook's parameter so reset always returns to the original starting value.- In App, spread or pass the returned members explicitly:
value={value}andonChange={onChange}on the input, andonClick={reset}on the button. - 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
