Home > Enterprise >  How can I solve useStae infinite rendering error
How can I solve useStae infinite rendering error

Time:07-25

I was trying to change text value in specific url. So I tried to use useState() but I'm getting this error.

react-dom.development.js:16317 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

How can I resolve this issue and change the value at a specific URL? I'll show you my code below.

import React,{useState} from 'react';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';


function MK(){

    const url = window.location.href;
    const [name,setName] = useState();
    if(url.includes('point')){
        //I want to change value here but getting error
        setName('error point');
    }

    return(
        <Form>
            <Form.Group className="mb-3" controlId="formBasicEmail">
                <Form.Label style={{color : 'white'}} id="label1">{name} 이름</Form.Label>
                <Form.Control style={{width:'30%'}}/>
            </Form.Group>

            <Form.Group className="mb-3" controlId="formBasicPassword">
                <Form.Label style={{color : 'white'}}> 설명</Form.Label>
                <Form.Control style={{width : '30%'}} as="textarea" rows={3} />
            </Form.Group>

            <Form.Group controlId="formFile" className="mb-3">
                <Form.Label style={{color : 'white'}}> 사진</Form.Label>
                <Form.Control style={{width : '30%'}} type="file" />
            </Form.Group>

            <Button variant="primary" type="submit">
            Submit
            </Button>
      </Form>
    );
}
export default MK;

CodePudding user response:

The thing is if the setName() is called. It triggers the rendering of the page and is called again setName(). This means the hook useState() called on every render, so it re-renders again and it is called indefinitely. To avoid this you can use another react State hook useEffect(). Which is triggered only once when the state loads example:

useEffect(() => {
    if(url.includes('point')){
        setName('error point');
    }
  }, []);

where the [] means it the definition inside the useEfect() method will be run only once.


More about infinite re-rendering can be seen here link.

CodePudding user response:

You are causing an infinite rerender by setting a value with a conditional at top level of your component.

You need to use useEffect hook for that:

React.useEffect(() => {
    if(url.includes('point')){
        //I want to change value here but getting error
        setName('error point');
    }},[url]) //If url changes, run useEffect

Use effect will run with every state change and initial render, and inside of it you can do some actions if something changes. In this case, if url changes, run the code inside

  • Related