...

/

The useState Hook Examples

The useState Hook Examples

Learn with example that how useState empowers developers to create dynamic and responsive React components, enhancing the overall user experience.

Making an avatar component

Let's say we want to display an image of a person that we have pulled from the internet. Most of the time, it will turn out to be a good picture (see the image below). However, sometimes, an image can be unavailable to download due to network or permission issues. When this happens, the browser throws a broken icon (the logo in the middle of the below image), which is not as nice to look at. The latest UX research shows that if we replace any broken image icons with something more unique (such as a user's name or initials, as shown on the right of the image below), this improves the user experience.

Press + to interact
An avatar component using useState
An avatar component using useState

To switch between an image and text, we can apply useState to define a condition. We will also need an event handler to notify us when an image URL is broken. If we put this logic together, we get an Avatar component:

const Avatar = ({ src, username }) => {
// State hook to manage the error state, initialized as false
const [error, setError] = useState(false);
// Event handler function triggered on image load error
const onError = () => {
setError(true);
};
// Return JSX content for the Avatar component
return (
<AvatarStyle>
{error ? (
<div>{username}</div>
) : (
<img
src={src}
alt={username}
onError={onError}
/>
)}
</AvatarStyle>
);
};

In the above code, first, we define a state, error, with useState. and then set the initial state to false, assuming that there's no error before loading the image. In the component's return, it follows this simple logic:

{ error ? A : B }

If error is true, it will display A ...