logo
logo

Form Input Validation with useEffect

Easy

Form Input Validation with useEffect

Easy

Prompt

Create a
ValidatedInput
component that validates user input and shows an error message if the input is invalid. Use the
useEffect
hook to perform validation whenever the input value changes, simulating
componentDidUpdate
behavior. This exercise will help you understand how to use the
useEffect
hook for performing validation based on changes in state and the importance of the dependency array.

Expectations

  • Validate user input based on a provided validation function.

  • Display an error message if the input is invalid.

  • Perform validation whenever the input value changes.

Background

Using
useEffect
to manage side effects like input validation is an essential skill for React developers. Validating user input is crucial for ensuring data quality and security in real-world applications, and this exercise will help you learn how to use
useEffect
for input validation in functional components.
Console
Submit
Solution
00:00

Solution Walkthrough for Form Input Validation with useEffect

Solution Explanation

Initialize state variables
value
and
isValid
: We create a state variable
value
using the
useState
hook and set its initial value to an empty string. We also create a state variable
isValid
to keep track of the input's validity.
const [value, setValue] = useState('');
const [isValid, setIsValid] = useState(true);
Validate input value with useEffect: We use the
useEffect
hook to perform validation whenever the input value changes. Inside
useEffect
, we call the provided
validationFunction
with the current input value and update the
isValid 
state accordingly. We include
value
and
validationFunction
in the dependency array to ensure the effect runs whenever either of them changes.
useEffect(() => {
  setIsValid(validationFunction(value));
}, [value, validationFunction]);
Create the input field and update the
value
state on change: We create an input field and update the
value
state with the input's value whenever it changes using the
onChange
event handler.
<input
  type="text"
  value={value}
  onChange={(e) => setValue(e.target.value)}
  className={isValid ? '' : 'error'}
/>
Display the error message if the input is invalid: We conditionally render the error message if the
isValid
state is false.
{!isValid && <p className="error-message">{errorMessage}</p>}
This solution demonstrates the key concepts of using the
useEffect
hook for managing side effects like input validation, controlling when the effect runs using the dependency array, and conditionally rendering error messages based on state changes.