...

/

Crafting a State in a Function Component

Crafting a State in a Function Component

Learn about the essential keypoints for implementing a state management system within a function component.

User actions and event handling

When we visit a typical web page, it asks for our username and password. After we log in, the website displays its content, such as blogs, tweets, or videos, in chronological order. We can vote on them and post comments—a very typical web experience these days.

When we surf a website like that as users, we don't put too much thought into how any of the actions are implemented, nor do we care about the order in which each is fired. However, when it comes to building the site ourselves, each action and the time at which each gets fired start to become important.

An action handlerA function or method that is responsible for handling a specific user action or event. These events can include actions like clicking a button, hovering over an icon, scrolling down a paragraph, typing on the keyboard, and more. fires when a user clicks a button, hovers over an icon, scrolls down a paragraph, types on the keyboard, and so on. A typical relationship between a user event and an action handler is illustrated in the following:

|--x---x---x-x--x--x------> user event
|--a---a---a-a--a--a------> action handler

In the figure above, basically, an x in the user event series is followed by an a in the user event series. Based on this, we can start to handle a user action. Let's turn ourselves to a "Hello World" Title component with a button inside. Each time we click the button, a counter is incremented by one and appended after "Hello World+", as shown in the figure below.

Press + to interact
Expected output result
Expected output result

To implement that, we start with a ...