DEV Community

Discussion on: 6 use cases of the useEffect ReactJS hook

Collapse
 
mrdulin profile image
official_dulin • Edited

You don't need an effect.

In this case, the better way for Running on state change: validating input field case is:

import { useEffect, useState } from "react";

const UseCaseInputValidation = props => {
    const [input, setInput] = useState('');
    const [isValid, setIsValid] = useState(false);

    const inputHandler = e => {
        const value = e.target.value;
        setInput(value);
        if(value.length < 5 || /\d/.test(value)) {
           setIsValid(false);
        } else {
           setIsValid(true);
        }
    };

    return (
        <>
            <hr />
            <h2>useEffect use case</h2>
            <h3>Running on state change: validating input field</h3>
            <form>
                <label htmlFor="input">Write something (more than 5 non numerical characters is a valid input)</label><br />
                <input type="text" id="input" autoComplete="off" onChange={inputHandler} style={{ height: '1.5rem', width: '20rem', marginTop: '1rem' }} />
            </form>
            <p><span style={isValid ? { backgroundColor: 'lightgreen', padding: '.5rem' } : { backgroundColor: 'lightpink', padding: '.5rem' }}>{isValid ? 'Valid input' : 'Input not valid'}</span></p>
        </>
    );
};
Enter fullscreen mode Exit fullscreen mode

Keep the input validation and state updating logic in the same place. Logical order and writing order are consistent.