Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

calling setState only once inside of useEffect–is there a better method?

In my react app I use the following pattern quite a bit:

export default function Profile() {
    const [username, setUsername] = React.useState<string | null>(null);

    React.useEffect(()=>{
        fetch(`/api/userprofiles?username=myuser`)
        .then(res=>res.json())
        .then(data => setUsername(data.username))
        },[])
        
    return(
        <div>
            {username}'s profile
        </div>
    )
}

When the page loads, some user data is fetched from the server, and then the page updates with that user data.
One thing I notice is that I only really need to call setUsername() once on load, which makes using state seem kinda excessive. I can’t shake the feeling that there must be a better way to do this in react, but I couldn’t really find an alternative when googling. Is there a more efficient way to do this without using state? Or is this the generally agreed upon way to load data when it only needs to be done once on page load

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Without using any external libraries, no – that is the way to do it.

It would be possible to remove the state in Profile and have it render the username from a prop, but that would require adding the state into the parent component and making the asynchronous request there. State will be needed somewhere in the app pertaining to this data.

The logic can be abstracted behind a custom hook. For example, one library has useFetch where you could do

export default function Profile() {
    const { data, error } = useFetch('/api/userprofiles?username=myuser');
    // you can check for errors if desired...

    return(
        <div>
            {data.username}'s profile
        </div>
    )
}

Now the state is inside useFetch instead of in your components, but it’s still there.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading