ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Custom Hook for Input Management

JSX

Goal -- WPM

Ready
Exercise Algorithm Area
1import React, { useState, useCallback } from 'react';
2
3/**
4* Custom hook for managing input field state.
5* Provides state, an update handler, and a reset function.
6* @param {string} initialValue - The initial value for the input field.
7* @returns {{value: string, onChange: function, reset: function}}
8*/
9function useInput(initialValue = '') {
10const [value, setValue] = useState(initialValue);
11
12// useCallback ensures the onChange function reference is stable
13// unless setValue changes (which it won't for useState).
14const onChange = useCallback((e) => {
15setValue(e.target.value);
16}, []);
17
18// useCallback ensures the reset function reference is stable.
19const reset = useCallback(() => {
20setValue(initialValue);
21}, [initialValue]);
22
23// Edge case: What if initialValue is null or undefined?
24// The useState hook handles this gracefully by defaulting to undefined if no arg is passed.
25// Our default '' handles common string cases.
26
27return {
28value,
29onChange,
30reset
31};
32}
33
34/**
35* A form component that uses the useInput custom hook.
36* @returns {JSX.Element}
37*/
38function ControlledForm() {
39// Use the custom hook for username input
40const usernameInput = useInput('');
41// Use the custom hook for email input
42const emailInput = useInput('');
43
44const handleSubmit = (event) => {
45event.preventDefault(); // Prevent default form submission
46alert(`Username: ${usernameInput.value}, Email: ${emailInput.value}`);
47// Reset fields after submission
48usernameInput.reset();
49emailInput.reset();
50};
51
52// Edge case: What if the form is submitted with empty fields?
53// The alert will show empty strings, which is acceptable for this example.
54// In a real app, validation would be added here.
55
56return (
57<form onSubmit={handleSubmit} className="controlled-form">
58<h2>User Registration</h2>
59<div className="form-group">
60<label htmlFor="username">Username:</label>
61<input
62id="username"
63type="text"
64value={usernameInput.value}
65onChange={usernameInput.onChange}
66placeholder="Enter username"
67/>
68</div>
69<div className="form-group">
70<label htmlFor="email">Email:</label>
71<input
72id="email"
73type="email"
74value={emailInput.value}
75onChange={emailInput.onChange}
76placeholder="Enter email"
77/>
78</div>
79<button type="submit">Register</button>
80</form>
81);
82}
83
84// Example of another input managed by the hook
85function PasswordInput() {
86const passwordInput = useInput('');
87const [showPassword, setShowPassword] = useState(false);
88
89const toggleShowPassword = () => {
90setShowPassword(!showPassword);
91};
92
93return (
94<div className="form-group">
95<label htmlFor="password">Password:</label>
96<input
97id="password"
98type={showPassword ? "text" : "password"}
99value={passwordInput.value}
100onChange={passwordInput.onChange}
101placeholder="Enter password"
102/>
103<button type="button" onClick={toggleShowPassword}>
104{showPassword ? 'Hide' : 'Show'}
105</button>
106</div>
107);
108}
109
110// Example of a textarea managed by the hook
111function BioTextArea() {
112const bioInput = useInput('');
113
114return (
115<div className="form-group">
116<label htmlFor="bio">Bio:</label>
117<textarea
118id="bio"
119value={bioInput.value}
120onChange={bioInput.onChange}
121placeholder="Tell us about yourself"
122rows="4"
123/>
124</div>
125);
126}
127
128// Example of using the hook with a different initial value
129function ProductCodeInput() {
130const productCode = useInput('DEFAULT-PROD-');
131
132return (
133<div className="form-group">
134<label htmlFor="productCode">Product Code:</label>
135<input
136id="productCode"
137type="text"
138value={productCode.value}
139onChange={productCode.onChange}
140/>
141</div>
142);
143}
144
145// Example demonstrating reset with a specific value
146function CounterInput() {
147const count = useInput(0);
148
149const increment = () => {
150count.onChange({ target: { value: String(Number(count.value) + 1) } });
151};
152
153const resetToTen = () => {
154// Note: useInput expects initialValue to be a string for setValue.
155// For numeric inputs, you might need adjustments or type casting.
156// Here, we simulate resetting to a string representation of 10.
157count.reset(); // Resets to initialValue (0)
158// To reset to a specific value, we'd need to modify useInput or call setValue directly.
159// For this example, let's assume reset() can take an argument or we call setValue.
160// Modifying useInput for clarity:
161// const reset = useCallback((newValue = initialValue) => setValue(newValue), [initialValue]);
162// For now, let's just show the reset functionality.
163alert('Resetting to initial value (0).');
164};
165
166return (
167<div className="form-group">
168<label htmlFor="count">Count:</label>
169<input
170id="count"
171type="number"
172value={count.value}
173onChange={count.onChange}
174/>
175<button type="button" onClick={increment}>Increment</button>
176<button type="button" onClick={resetToTen}>Reset (to 0)</button>
177</div>
178);
179}
Algorithm description viewbox

Custom Hook for Input Management

Algorithm description:

This scenario focuses on creating and using a custom hook, `useInput`, in React. The `useInput` hook encapsulates the logic for managing the state of a single input field, including its value, an `onChange` handler, and a `reset` function. This promotes code reuse and keeps components cleaner. The `ControlledForm` component then utilizes this custom hook to manage multiple input fields (`username`, `email`), demonstrating how custom hooks abstract away common patterns. This is a fundamental technique for building reusable logic in React applications, applicable to any form or interactive element that requires state management.

Algorithm explanation:

The `useInput` hook initializes a state variable `value` using `useState`. It returns an object containing the current `value`, an `onChange` handler (wrapped in `useCallback` for performance optimization), and a `reset` function (also wrapped in `useCallback`). The `onChange` handler updates the state with the input's current value. The `reset` function sets the state back to its `initialValue`. In `ControlledForm`, `useInput` is called twice, once for `username` and once for `email`. The returned `value` and `onChange` properties are destructured and passed to the respective `<input>` elements, making them controlled components. The `reset` function is used in the `handleSubmit` handler. The time complexity for each input operation (typing, resetting) is O(1). The space complexity is O(1) per hook instance. Edge cases like initial empty values are handled by `useState` defaults and explicit initial values.

Pseudocode:

HOOK useInput(initialValue):
  STATE value = initialValue

  FUNCTION onChange(event):
    SET value = event.target.value
  END FUNCTION

  FUNCTION reset():
    SET value = initialValue
  END FUNCTION

  RETURN { value, onChange, reset }
END HOOK

COMPONENT ControlledForm():
  usernameInput = useInput("")
  emailInput = useInput("")

  FUNCTION handleSubmit(event):
    PREVENT default submission
    ALERT with usernameInput.value and emailInput.value
    CALL usernameInput.reset()
    CALL emailInput.reset()
  END FUNCTION

  RENDER:
    A form with onSubmit = handleSubmit
      An input for username:
        value = usernameInput.value
        onChange = usernameInput.onChange
      An input for email:
        value = emailInput.value
        onChange = emailInput.onChange
      A submit button
  END RENDER
END COMPONENT