DeployU
Interviews / Frontend Engineering / This form doesn't reset correctly. Fix the bug and refactor to a more robust solution.

Questions

This form doesn't reset correctly. Fix the bug and refactor to a more robust solution.

debugging State Management Interactive Quiz Code Examples

A developer has built a SurveyForm component. The form has several pieces of state: name, email, and rating.

After the user clicks “Submit”, the form should completely reset to its initial, empty state. However, a bug was reported: after submission, the name and email fields clear, but the rating field remains filled.

The current implementation uses a manual handleReset function, which is becoming hard to maintain as more fields are added.

This is a two-part challenge:

  1. Fix the Bug: Identify why the rating field is not resetting and apply the immediate fix.
  2. Refactor: The manual reset approach is brittle. Refactor the application to use a more declarative and robust React pattern for resetting the component’s entire state at once, without needing to manually reset each state variable.
Survey Form - Fix Reset Bug and Refactor
Your Code
import React, { useState } from 'react';

// The form component with a buggy reset logic
function SurveyForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [rating, setRating] = useState(0);

  const handleReset = () => {
    setName('');
    setEmail('');
    // THE BUG: The developer forgot to reset the rating state.
  };

  return (
    <div>
      <form>
        <input
          type="text"
          placeholder="Name"
          value={name}
          onChange={e => setName(e.target.value)}
        />
        <br />
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={e => setEmail(e.target.value)}
        />
        <br />
        <select value={rating} onChange={e => setRating(e.target.value)}>
          <option value={0}>Select rating...</option>
          <option value={1}>1 Star</option>
          <option value={2}>2 Stars</option>
          <option value={3}>3 Stars</option>
        </select>
      </form>
      <button onClick={handleReset}>Reset Form</button>
    </div>
  );
}

export default function App() {
  return <SurveyForm />;
}
// Validate the refactored solution using the key prop pattern
const code = document.querySelector('[data-editor]').textContent;

// Check that the solution uses the key prop pattern (best practice)
if (!code.includes('key={') && !code.includes('key =')) {
  throw new Error('Test failed: Refactor to use the key prop pattern for robust form reset. The parent should manage a formKey state.');
}

// Check for formKey or similar state in parent
if (!code.includes('formKey') && !code.includes('resetKey') && !code.includes('componentKey')) {
  throw new Error('Test failed: Create a state variable (formKey) in the parent component to use as the key prop.');
}

// Verify the key changes to trigger reset
if (!code.includes('setFormKey') && !code.includes('setResetKey') && !code.includes('setComponentKey')) {
  throw new Error('Test failed: The parent should update the key state to trigger a reset.');
}

// Success!
console.log('✓ All tests passed! Form reset refactored using the key prop pattern.');
console.log('✓ This declarative approach is more robust and scales better.');
Click "Run Code" to see output...
Click "Run Code" to see test results...
Wrong Approach

import React, { useState } from 'react'; // The form component with a buggy reset logic function SurveyForm() { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [rating, setRating] = useState(0); const handleReset = () => { setName(''); setEmail(''); // THE BUG: The developer forgot to reset the rating state. }; return ( <div> <form> <input type="text" placeholder="Name" value={name} onChange={e => setName(e.target.value)} /> <br /> <input type="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} /> <br /> <select value={rating} onChange={e => setRating(e.target.value)}> <option value={0}>Select rating...</option> <option value={1}>1 Star</option> <option value={2}>2 Stars</option> <option value={3}>3 Stars</option> </select> </form> <button onClick={handleReset}>Reset Form</button> </div> ); } export default function App() { return <SurveyForm />; }

Right Approach

import React, { useState } from 'react'; // The form component no longer needs to know how to reset itself. // It's just a simple, self-contained form. function SurveyForm() { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [rating, setRating] = useState(0); return ( <form> <input type="text" placeholder="Name" value={name} onChange={e => setName(e.target.value)} /> <br /> <input type="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} /> <br /> <select value={rating} onChange={e => setRating(e.target.value)}> <option value={0}>Select rating...</option> <option value={1}>1 Star</option> <option value={2}>2 Stars</option> <option value={3}>3 Stars</option> </select> </form> ); } // The parent component now fully controls the reset behavior. export default function App() { // 1. Create a state variable to use as the key. const [formKey, setFormKey] = useState(0); const handleReset = () => { console.log('Form reset!'); // 2. To reset the form, just change the key. setFormKey(currentKey => currentKey + 1); }; return ( <div> {/* 3. Pass the state variable as the key prop. */} <SurveyForm key={formKey} /> <button onClick={handleReset}>Reset Form</button> </div> ); }

Practice Question

In React, what is the effect of changing a component's key prop?