Home > Software design >  Why does useState react hook cause Too many re-renders. React limits the number of renders to preven
Why does useState react hook cause Too many re-renders. React limits the number of renders to preven

Time:09-26

I am having the following script

    const [setList, setSetList] = useState({ data: null });
    const [currentUser, setCurrentUser] = useState({ data: null });
    const [username, setUserName] = useState();
    
    const Token = localStorage.getItem('token')
    console.log(Token)
    useEffect(() => {
        const fetchData = async () => {
            const setlist = await axios.get(
                'http://127.0.0.1:8000/api/set/list/', {
                    headers: {
                        Authorization: `Token ${Token}`
                    }
            });
            const setuserdata = await axios.get(
                'http://127.0.0.1:8000/api/user/current/', {
                    headers: {
                        Authorization: `Token ${Token}`
                    }
            });
            setCurrentUser({ data: setuserdata.data });
            setSetList({ data: setlist.data });
            };
            
            fetchData();
        }, []);
        
        console.log('render');
    if (currentUser.data) {
        console.log("userdata", currentUser.data);
        console.log("userdata", currentUser.data.username);
        **setUserName(currentUser.data.username);**

    }

trying to call the setUserName causes the Too many re-renders. React limits the number of renders to prevent an infinite loop.. I can't seem to find the reason why.

CodePudding user response:

Because you're calling setUserName on every render. And setting the state triggers a re-render. So on every render you're triggering a re-render.

If you want something to trigger when currentUser.data changes then don't check for it on every render, check for it in a useEffect hook. For example:

useEffect(() => {
  // currentUser.data has changed, update something
}, [currentUser.data]);

But in this particular case you don't need any of this at all. You're duplicating values in state:

const [currentUser, setCurrentUser] = useState({ data: null });
const [username, setUserName] = useState();

Since username is part of currentUser then you don't need username, because you have currentUser. Just remove the username state entirely and any code that's setting/using it, and refer to currentUser.data.username instead.

If you want to have shorthand for username so you don't have to write currentUser.data every time, then instead of tracking it in state just set a value when rendering:

const username = currentUser?.data?.username;
  • Related