React Hooks for beginners, Sweet and a little complex

Hossein Ahmadi
Webtips
Published in
6 min readJul 7, 2019

What are Hooks?

React has been introduced around 5 years ago and nowadays is one of the most popular JS front end libraries. React with all of its great and amazing features walked through developer’s life and right now that I’m writing for you earned +132k stars in GitHub.

Main concept of react is based on Components. Something that let you to write reusable codes and make your project clean. As you know there are 2 types of components in react: Class-Based Components and Functional Components. Class-Based components are a little older than functional components and as we except they have some excluded features that functional components can’t use them.

But functional components are cleaner and faster and sweeter than classes. So, React has introduced Hooks. Hooks are something that let you write Functional Components and still hook into class-based features and use them. Great! Now with React Hooks we can write cleaner and simpler components by using functions and still use wonderful features of Class-based components, Specifically States and Stateful Logic!

Why should we use hooks and functional-components?

If you walk through react official documents and read about Hooks and Functional-Components you can see some enough reasons to use them. But let me show you some real examples that help you understand reasons deeply.

First. Less and Cleaner Code: We want to build a component that renders a title and a subtitle. First, we write it by class:

Now our functional Component:

Alright! I don’t explain more. It’s clear which one is cleaner!

Second. Hierarchy and stateful logics: As mentioned in react docs:

React doesn’t offer a way to “attach” reusable behavior to a component

What does it mean? Think about 3 components that everyone contains a form and every form contains a name filed. You store the value of your input in state of your components. So, you have 3 class-based components with state (includes name) and handleNameChange handler. Instead of writing this same code over and over every time you want to use the name field in your project just use hooks! Write one hook and import it in any functional component and you can use the name and its handler behavior!

Third. Class-Based Components are complex!: Yes! Classes are complex. When you want to write a class-based component you need to understand core concepts of word “this”, lifecycles like componentDidMount or componentDidUpdate, binding methods and so on. But in functional components you just work with functions! Specially arrow functions. There is no “this” and There is no binding. But there is no state and lifecycle neither! What if we want to fetch an API after mounting our component? What if we want to have forms and do validation and something with their value in state? Don’t worry. Just use hooks useState instead of states and setState and use Effect instead of lifecycle methods.

Fourth. Sweet experience for developers that move up to down: For someone like me that move in the project tree and develops step by step from UP to DOWN, using react hooks can be a great experience. Let me explain more. Up to down means I write my bigger components first. So, I use a pattern in all of my projects that tells me: Complete base of your navigation and routing first, do your job in bigger components and then hit other small components.

So, when I start my project I’ll go to my router. But for testing and verifying my router I need some components! Then I have to create my base components first. As we see above, functional components are cleaner and faster therefore I use them to speed up my development. After completing router, I head back to my base and important components and Ooops!!! I need form in this one and I have to convert it to class! I need stateful logic in this one and I have to convert it to class! But now with hook, developing react apps can be more enjoyable for me and people like me!

Note 1: You don’t have to use hooks! There isn’t any pressure by react team on you to migrate and convert your codes to use hooks. Even they encourage you to read and search about hooks and walk slowly through new world of react. You can write and use hooks beside your class-based components (NOT IN THEM) to see how it works and which you prefer.

Note 2: There’s discuss about the performance of functional and class-based components. You can read this great article by Philippe Lehoux: 45% Faster React Functional Components, Now

Note 3: Don’t forget to read some important rules of using hooks in this article in official documents: Rules of Hooks

Definition of useState

And now let’s see some simple practical codes using useState in react. See this:

This is react docs example for useState and counts from zero by clicking on the button. Class type of code is here too:

You see useState(), count, setCount and some brackets.

UseState(): this is a function that is provided by react team in react library and you have to import it first. Returns an array and its argument is the initial value of state.

Count: the name of our variable in state

SetCount: a function that implements our stateful logic. The input of setCount is our state’s new value.

Brackets: brackets are some simple array destructuring! You can read about this in Destructuring assignment in JavaScript. As I mentioned above every useState() returns an array! So, by using this bracket we are using first value of array ([0]) as value of our state and second ([1]) is the method we define to change our state.

Therefore, in this example we’re telling that our component has state that includes count and we want to handle changes of it by setCount method.

Some examples of useState and our own hooks

Now let me show you some useful implementation of useState. In this example we create our hooks by using useState, so you can see the reusability and flexibility of hooks too.

Consider we want to have a counter that receives start, finish and step and count by clicking a button. This is our main component:

Please note that useCounter is our custom hook that receives 3 arguments: start, finish and step.

Our array destruction means that our hook returns an array that first item is value of count and second one is the method of changing state (Our State Logic).So we use this method- with our arbitrary name of handleCount- as the onClick event handler. Therefore, it’s time to see our custom hook implementation:

We see 3 parts in this code:

  1. Definition of our state: from what you have read in this article this line means: we have a count variable in our state that its initial value is value of “start” and we want to change our state by setCount method.
  2. Implementation of our handleCount method. We use a condition to check if we reached our finish amount or not. Then we use setCount to change the value of count according to if condition result.
  3. Return our custom hook array: as you see first is the value of count and second is our handleCount method.

This is what we see when we run our app:

Result of our codes

Wrap Up

Awesome! Everything in this article is the base and core concept of react hooks for beginners and developers who are afraid of changes. You can read more about this subjects or other subjects about hooks in React Documentation and other sources. I’ll try to describe useEffect in the future because it’s not possible to cover it in this article. Just walk through Hooks and start to rewrite some of your codes with react new feature to see its power and sweetness.

--

--