Home > other >  calling setState only once inside of useEffect--is there a better method?
calling setState only once inside of useEffect--is there a better method?

Time:01-04

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

CodePudding user response:

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.

  • Related