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.
Exercise
Add a second button named “Decrement” in the above code example. Each button click should reduce the count by 1.
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.
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.