React JS III: React Hooks

30th Jul 18
person working on the computer

In this article I go through a way to include state into your React functional component

React Hooks

There is a way to manage state in functional components using React hooks.  So just as an example I will change the App component from a class based component to the functional component.  And I will import a hook called 'useState' from the React library which will allow use to use a state within the functional component.  I call it like a function and pass the state as an argument.  The hook will then return an array with two elements.  The first element will be our current state and the second will be a function that allows us to update the state.  So by using ES6 destructuring you can pull those two elements out of the array.

To update the state I add the function previously created assigned to a variable not a property of a class.  I then refer to its variable name without 'this.state' as that's no longer applicable.  Finally rather than using 'this.setState' in the function, I refer to the variable name which has the second element of the hook assigned to it and passing in the new state data.

The difference between the useState hook and the class component state is that when the hook updates the state with the new state data rather than merging it.   Therefore if you don't include all of the states values in the update function you will loose those properties/values you didn't include.

Screenshot of the use of hook useState in functional component

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.