10. Efficient Form Validation with Yup and Managing State using useState

Introduction: Form validation plays a crucial role in ensuring that user input meets specific requirements. In this blog post, we will explore how to validate user-entered numbers using the Yup package, a powerful and popular validation library in the React ecosystem. Additionally, we will discuss the useState hook, which is a fundamental React hook used for managing state and updating the user interface dynamically.

Section 1: Validation of User-Entered Numbers with Yup

To perform validation using Yup, we need to define a schema that outlines the validation rules for our form. Let's create a schema to validate the length of a password as an example:

import * as Yup from 'yup';

const PasswordSchema = Yup.object().shape({
  passwordLength: Yup.number()
    .min(4, 'Should be a minimum of 4 characters')
    .max(16, 'Should be a maximum of 16 characters')
    .required('Length is required'),
});

In the above code, we define a schema object using Yup.object().shape(). Inside the shape, we specify the property passwordLength and apply validation rules using Yup.number(). We set a minimum length of 4 characters, a maximum length of 16 characters, and make it a required field using .required().

Section 2: Managing State with useState

The useState hook is a built-in React hook that allows us to add state to functional components. It enables us to update and manage the UI dynamically based on changes in the state. Let's see how to use the useState hook:

import React, { useState } from 'react';

function MyComponent() {
  const [variable, setVariable] = useState('');

  // ... rest of the component code

  return (
    <div>
      {/* JSX elements */}
    </div>
  );
}

In the code above, we import the useState hook from the 'react' library. Inside the component function, we declare a state variable called variable and a corresponding function called setVariable to update the state. The initial value of variable is set to an empty string ('').