Error in react app due to rendition issue

Viewed 9

I'm getting render error "Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop." for my react app although the app is getting compiled correctly, could anyone please advise me on the same as I'm new to react. Below is my source code where the error is coming from as per the browser console for reference.

import { useState } from "react";
import Card from "./shared/Card";
import Button from "./shared/Button";

const FeedbackForm = () => {

    const [text, setText] = useState('');
    const [btnDisabled, setBtnDisabled] = useState(true);
    const [message, setMessage] = useState('');

    if(text === '') {
        setBtnDisabled(true);
        setMessage(null)
    } else if(text !== '' && text.trim().length <= 10) {
        setBtnDisabled(true);
        setMessage('Text must be atleast of 10 characters!');
    } else {
        setBtnDisabled(false);
        setMessage(null)
    }

    const handleTextChange = (e) => {
        setText(e.target.value)
    }
    
    return (
        <Card>
            <form>
                <h2>How would you rate your service with us?</h2>
                <div className="input-group">
                <input type='text' onChange={handleTextChange} placeholder='Write a review' value={text} />
                <Button type='submit' isDisabled={btnDisabled}>Send</Button>
                </div>              
                {message && <div>{message}</div>}
            </form>
        </Card>
    )
}

export default FeedbackForm;
1 Answers

Your if block runs every time you render. Since you are calling setState in the if block, it will cause your component to render again, hence you are getting infinite rerenders.

In your case you can use useEffect to have it run every time the your text changes.

useEffect(() => {
    if(text === '') {
        setBtnDisabled(true);
        setMessage(null)
    } else if(text !== '' && text.trim().length <= 10) {
        setBtnDisabled(true);
        setMessage('Text must be atleast of 10 characters!');
    } else {
        setBtnDisabled(false);
        setMessage(null)
    }
}, [text]);
Related