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

Before hooks to use any state or lifecycle events you have to create a class component. But noe we can use these features within functional components.

The useState Hook :

The useState Hook allows us to use state inside our functional component.
Example Usage:

import React, { useState } from ‘react’;

function Layout() {

const [sideBarOpen, setSideBarOpen] = useState(false);

return (
<div>
    <Header />
    <button onClick={()=> setSideBarOpen(!sideBarOpen)}>
        Toggle sidebar
    </button>
    <div className={sideBarOpen?”:’d-none’}>
        <Sidebar />
    </div>
</div>
);
}

In the above example we have called the useState hook. The useState hook will take a default state value and returns an array with two values.

The first one is the state with the default value passed to useState and the second item is a function used to change the state.

Here we are using array destructuring to get the two values with the names we want. It is generally used naming convention to name the state with appropriate name and the function is the state name prefixed by set.

We can use the state variable as the state in class component and whenever we need to change it call the set function with the new value. This is similar to setState in class component but won’t merge the state.

The useEffect hook :

The Effect Hook lets you perform side effects in function components.

Whenever we need to perform actions based on state change or performing changes outside component then we can use the useEffect hook.

The useEffect hook can also be used as the lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount.

function Header(props) {
const [sidebarOpen, setsidebarOpen] = useState(false)
useEffect(() => {
props.handleToggleSidebar(sidebarOpen)
}, [sidebarOpen, props])

return (
<div className="col-md-1 admin-bars">
<button className="button-field" onClick={(e)=> setsidebarOpen(!sidebarOpen)}
>
<i className="fa fa-bars" />
</button>
</div>
)
}

Here we are calling a method on the parent component based on the state change in the current component.

We can use useEffect as componentDidMount by passing an empty array as the second parameter.

useEffect can be used as componentWillUnmount by returning a function which performs the actions needed for component cleanup.

Rules of Hooks :

Hooks are plain javascript functions, but to use hooks properly we need to follow two rules.

  • Hooks should always be called in the top level of the component. They should not be called inside conditions and loops.
  • Hooks should not be called in normal functions unless they are custom hooks.

There are reasons for these two rules which you can check in the official react Docs.

There are some other default hooks provided by react but they are not used that much.