UseState React Hook
React hooks, The game-changer of using react without class components. React hooks allow us to be able to use state and other react features without using a react class component. React hooks were introduced with version 16.8. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. Hooks also offer a new powerful way to combine them.
I am going to talk about the useState hook and how I was able to understand what is going on. For both examples below, we are using the old fashion class component to display a button and the count. When the button is clicked it updates the state of count and immediately displays the number.
In the picture above, we have a class component App initialized with a constructor and setting “this.state” to count 0. Then inside of the render we display a button and a paragraph displaying the current count(this.state.count). Inside of the button, we have an onClick to this.setState to increase the count by 1 each time the button is clicked.
Below is another example that does the exact thing the code above does. Except within the picture below we are using the useState hook. First import the { useState } from react. It lets us keep the local state in a function component.
I defined an ES6 function called App that returns a div with a button and the count. We declare a new state variable by calling the useState Hook. It returns a pair of values, to which we give names. We’re calling our variable count because it holds the number of button clicks. We initialize it to zero by passing 0 as the only useState argument. The second returned item is itself a function. It lets us update the count so we’ll name it setCount. When the user clicks the button, we call setCount with a new value, count + 1. React will then re-render the App component, passing the new count value to it.
Me personally, after learning a little more about hooks I love them. Look at the difference between both sets of code, you can really see how much code you get rid of. The convenience of being able to hook into state whenever I can is a really great feature. The biggest thing about react hooks is that we can hook into the state without having to recreate a class component with all the extra code.
Here is a link to learn more about react hooks: https://reactjs.org/docs/hooks-intro.html