DEV Community

Melvin Kosisochukwu
Melvin Kosisochukwu

Posted on • Updated on

A Dive Into React Hooks

If you have ever worked with React State, you must have come across ‘this’ binding. Personally, I do not like the use of classes in React and somewhere out in the world, there are people who don’t fancy using classes in React as much as I do. You're in luck, with the addition of React hooks that gets rid of the classes, ‘this’ binding and still does the same works that react states do with shorter, cleaner code.
React hooks is an addition that was introduced with React 16.8. They let you use state and other React features without writing a class.
Generally using classes in react results to a lot of lines of code that can be easily cut down using a function. A simple hello world program will look like this with classes and state.

Alt Text

When using a function and React hooks you can optimize this same code down to:

Alt Text

If you observe the two codes you can clearly see that Hooks make things easier for you with shorter, faster code.
Now let’s go into how React hooks actually work, what you should know before using react hooks.
Before you decide to use React Hooks there a JavaScript principle you should already be proficient in and that is destructuring.
What is destructuring? This is simply unpacking the values of an array or object into a distinct value. There is a really good article on destructuring here.
React hooks uses the principles of destructuring to unpack values from the useState() function.

Alt Text

The left side is where the variable name is declared. The first item is the variable name for the state and the second item in the array separated by a comma is the function for setting the value of the state, this serves the same purpose as the setState() function in classes.
The right side is where the destructured array (useState function). The parameter for the function is where the value for the state is initialized. It might take a little getting used to but when you start using the hooks it gets a little bit easier.
The setValue function can be used to update the value of the state.

Alt Text

The setValue function is called on button click and updates value from ‘World’ to ‘Earth’.
For further insight on react hooks, you can check out the documentation from the React Team.

Discussion (10)

Some comments have been hidden by the post's author - find out more