Home > Software engineering >  what is the correct way to collect input data WITHOUT LAG on typing in REACT?
what is the correct way to collect input data WITHOUT LAG on typing in REACT?

Time:06-21

so it's been a month i'm working with react.

there is a problem i didn't know what to do with it.

in onChange event handlers EVEN in the smallest page and project there is a delay in typing and specially Delay in Removing text.

why is this happenig ? i mean react is popular because of Fast UI right? so what we should do to handle Forms without this Perfomance Problem ?

why there is a lag in this form ?

const LoginForm = () => {
  // State & Validate Schema
  const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
      rememberMe: false,
    },
    validationSchema: Yup.object({
     blah blah some validation
    }),
    onSubmit: (value) => {
       console.log(value, "Submitted");
    },
  });

  return (
    <>
      <Container maxWidth="sm" disableGutters>
        <Box>
          <h3>Log to the Account</h3>
          <form onSubmit={formik.handleSubmit}>
                <TextField
                error={formik.touched.email && formik.errors.email !== undefined}
                name='email'
                label='Email'
                value={formik.values.name}
                onBlur={formik.handleBlur} // If Input is Touched Show Error
                onChange={formik.handleChange}
                helperText={formik.touched.email && formik.errors.email}
                autoComplete="on"
                              />
                <TextField
                error={formik.touched.password && formik.errors.password!== undefined}
                name='password'
                label='Password'
                value={formik.values.password}
                onBlur={formik.handleBlur}
                onChange={formik.handleChange}
                helperText={formik.touched.password&& formik.errors.password}
                autoComplete="on"
                              />
                  <Button type="submit" variant="contained" size="medium">
                    Login
                  </Button>
                  <span>Remember Me</span>
                  <Checkbox
                    value={formik.values.rememberMe}
                    name="rememberMe"
                    onChange={formik.handleChange}
                  />
          </form>
        </Box>
      </Container>
    </>
  );
};

CodePudding user response:

I think this is not a problem of react rather than Formik. In your example you have a variable named formik to pass the current value to your TextField component you define the prop value={formik.values.someName} and to update the field value you specify an onChange={formik.handleChange} handler. To be able to pass the new value after a change to your input field, the formik variable needs to be updated and this causes your whole form component to be rerendered on every key stroke.

To be honest, I switched for similar reasons from Formik to React Hook Form some while ago and hadn't used Formik for a long time. But I think your performance problems are caused by the design of Formik.

CodePudding user response:

As you are using MUI Formik Yup,

Performance may get Affected & totally Depend on your CPU You can Consider the following code For Login, based on the same Libraries

    //password validation
     const lowercaseRegEx = /(?=.*[a-z])/;
     const uppercaseRegEx = /(?=.*[A-Z])/;
     const numericRegEx = /(?=.*[0-9])/;
     const lengthRegEx = /(?=.{6,})/;


const validationSchema = Yup.object({

    email: Yup.string().email('Invalid Email').required('email is required'),
    password: Yup.string()
        .matches(
            lowercaseRegEx,
            "Must contain one lowercase alphabetical character!"
        )
        .matches(
            uppercaseRegEx,
            "Must contain one uppercase alphabetical character!"
        )
        .matches(numericRegEx, "Must contain one numeric character!")
        .matches(lengthRegEx, "Must contain 6 characters!")
        .required("Required!")
})


  const { errors, values, handleBlur, handleSubmit, handleChange, touched, dirty, isValid } = useFormik({
    initialValues: {

        email: '',
        password: ''
    },
    validationSchema,
    onSubmit: handelLogin
})


<Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 3 }} >
                        <Grid container spacing={2}>

                            <Grid item xs={12}>
                                <TextField
                                    error={(errors.email && touched.email) ? true : false}
                                    required
                                    fullWidth
                                    id="email"
                                    label="Email Address"
                                    name="email"
                                    autoComplete="email"
                                    value={values.email}
                                    onChange={handleChange}
                                    onBlur={handleBlur}
                                />
                            </Grid>

                            {errors.email && touched.email ? (
                                <Alert variant='string' severity='error' sx={{ color: '#f44336' }}>{errors.email}</Alert>
                            ) : null}

                            <Grid item xs={12}>
                                <TextField
                                    type='password'
                                    error={(errors.password && touched.password) ? true : false}
                                    required
                                    fullWidth
                                    id="password"
                                    label="Password"
                                    name="password"
                                    autoComplete="password"
                                    value={values.password}
                                    onChange={handleChange}
                                    onBlur={handleBlur}
                                />
                            </Grid>
                            {errors.password && touched.password ? (
                                <Alert variant='string' severity='error' sx={{ color: '#f44336' }}>{errors.password}</Alert>
                            ) : null}


                        </Grid>

                        <LoadingButton
                            sx={{ mt: 3, mb: 2 }}
                            disabled={!dirty || !isValid}
                            onClick={handelLogin}
                            fullWidth
                            loading={isLoading}
                            variant="contained"
                            type='submit'
                        >
                            Log In
                        </LoadingButton>

                        <Grid container justifyContent="space-between">
                            <Grid item>
                                <RouterLink to={"/forgotpass"} style={{
                                    textDecoration: "none", color: "#1976d2"
                                }}>

                                    <Typography paragraph>
                                        Forgot password
                                    </Typography>
                                </RouterLink>

                            </Grid>
                            <Grid item>
                                <Typography paragraph>
                                    <RouterLink to={"/resetpass"} style={{
                                        textDecoration: "none", color: "#1976d2"
                                    }}>

                                        Reset Password

                                    </RouterLink>
                                </Typography>

                            </Grid>
                        </Grid>
                    </Box>
                </Box>
  • Related