First Look at React Hooks Usage

Rate this post

Build a counter application with React Hooks to increment the current count value on the click of a button.

Managing state with React Hooks

The following example demonstrates managing state with React Hooks using useState hook.

The useState hook is an alternative to using this.state or this.setState in class components.

The useState hook returns the current value of the state and a function to update the state.

Run the application to see it in action.

React counter increment using functional component with hooks

Exercise

Add a second button named “Decrement” in the above code example. Each button click should reduce the count by 1.

React counter increment and decrement using functional component with hooks

Managing side effects with React Hooks

Take the previous example and add some side effects logic.

Assume a message needs to be shown when the count is greater than 5.

Read the current value of the count on each render. Then, set the message state if the count reaches more than 5.

The useEffect hooks allow you to achieve this by creating an inline callback function.

In the code exercise below, the useEffect function will run each time the state count or message is changed.

React counter increment and decrement  with  message when greater than 5 using functional component with hooks

Exercise

Implement a “Reset” button that will allow the user to start over. When clicked, the application should set the count to zero and set the message to an empty string.

React counter increment, decrement and reset counter using functional component with hooks

Leave a Comment

17 + 14 =

CRICKET LIVE STREAMING