DEV Community

Cover image for Why React Hooks ?
Nkenganyi Clovis
Nkenganyi Clovis

Posted on • Updated on

Why React Hooks ?

In this article, we will look at why using React Hooks can be so effective and help us to write cleaner code.
We will also end up by looking at the importance of React Hooks in our business logic when writing React code.

What are Hooks?

Hooks are a new addition in React 16.8.
They let you use state and other React features without writing a class.

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.

Some basic React Hooks include:
useState
useEffect
useContext

In general, React Hooks allow us to write shorter and cleaner code.

What is a useState Hook ??
const [state, setState] = useState(initialState);
useState returns a stateful value, and a function to update it.

What is a useEffect Hook ??
useEffect(didUpdate);
Accepts a function that contains imperative, possibly effective code.

What is a useContext Hook ??
const value = useContext(MyContext);
Accepts a context object (the value returned from React.createContext) and returns the current context value for that context.

Let's look at the example below of a simple counter component using the class syntax and compare it when using Hooks.
In this example, we will be using the useState Hook

NB: Using class syntax

import React, { Component } from 'react'

class MyClassComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 0,
    }
    this.incrementCount.bind(this)
  }

  incrementCount() {
    this.setState((state) => {
      count: state.count + 1
    })
  }

  render() {
    return (
      <div>
        <p>Counter: {this.state}</p>
        <button onClick={this.incrementCount}>Increment Count</button>
      </div>
    )
  }
Enter fullscreen mode Exit fullscreen mode

We set an initial value for our count state in the constructor and have an incrementCount method we can call when the button is clicked to increment that state. Still, for something as simple as a counter, there’s a lot of code we have to write to get it to work, including knowing about class constructors, making sure we don’t forget to call super(props), and binding this correctly to incrementCount.

NB: Same example using useState Hook

import React, { useState } from 'react'

function MyFunctionComponent() {
  const [count, setCount] = useState(0)
  const incrementCount = () => setCount((countState) => countState + 1)

  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={incrementCount}>Increment Count</button>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

That’s so much more straightforward! I have a single call to useState (all hooks start with the word use to signify they are in fact hooks) which returns an array with two elements in it. The first is a reference to the state being managed, which we named count. The second is a function to change that state, which we named setCount. Additionally, any value passed into useState when it’s called - 0 in our example is used as the initial state.

setCount It’s very similar to "this.setState" in that it allows us to update our state over time. However, while this.setState will merge any state changes for you, setCount (or any state setting function from useState) always overwrites the previous state. "incrementCount" is now a function in our component instead of a class method.

The useState hook gives us all the state management features of class components in our function components and will continue to be a building block for more advanced hook use cases.

Above, we have just done a simple demonstration using useState hook how easy hooks can be in building components in React

Importance Of React Hooks 0n business logic in React code

If we consider the types of components we create, they fall into two general categories. The first category contains what are sometimes described as “stateless” or “dumb” components. These components are typically functions that hold no state, do not interact with their environment except by accepting props, and are chiefly concerned with displaying our UI. The second category contains “stateful” or “smart” class components which hold business logic to interact with the environment, handle data fetching, provide user interactivity, etc. It’s important to note that while our UI code is easily composable using our stateless components, our business logic is actually locked into the stateful components in which it is written. How do we then share this business logic (read: how do we compose this logic) across our application? Throughout React’s lifetime, this has been handled in a few different ways.

Hooks stepped in and provided a better alternative for sharing business logic. We no longer rely on components to encapsulate our logic which injects more complexity into our component tree, either implicitly or explicitly. Instead, hooks exist as functions that can be called within components, shared across components and themselves composed into more complicated hooks - oh yes, custom hooks exist and they are wonderful - without affecting the component tree. All calls to hooks are explicit so dependencies aren’t hidden and give the developer naming flexibility so there’s no prop clobbering. Hooks are brand new, so there will undoubtedly be rough edges and scenarios we haven’t even considered yet but they will only improve as they reach full community adoption.

The initial look and feel of hooks are fantastic. They are the most composable paradigm for sharing business logic and allow everything to React to be encapsulated as functions, both UI components and business logic. This move towards functions has been the evolutionary trend of React throughout its life and hooks are a natural outcome of that evolution. They are incredibly powerful and I can’t wait to see how we as the community use them to write better software.

If you love this article, please do well to like and comment.
I'll be coming up with much more useful and educative articles on web development.

visit my website nkenganyiclovis.tech
Follow me on Twitter @Nkenganyi Clovis
Follow me on LinkedIn @Nkenganyi Clovis

Signup on daily dev to get the latest updates and news as a software developer daily.dev

Top comments (0)