Some Useful React Hooks, Its Rules and Features

Dipta Dwiyantoro
3 min readMay 25, 2021
Source :

Nowadays, function-based component in react has been used as a main pattern rather than class-based component because function-based component have less code rather than class-based component and also because we write less code, the bundle that our app create is more smaller than using class-based.

Building React App using function-based component have different coding style and paradigm. For example, there are some build-in function and state in class-based component but in the function-based component there are gone. Here’s come React Hooks.

React Hooks is a feature in React 16.8 to let us use class-based feature such as state and life-cycle function without writing a class. There are some rules if we want to use Hooks

  • Only Call Hooks at the Top Level
    Don’t call Hook inside loops, conditions or nested functions. You need to ensure the Hooks are called when the component is rendered.
  • Only Call Hooks from React Functions
    Don’t call Hook inside regular JavaScript functions. Called it from React Component Function or Custom Hooks.

That rules are defined according to the Hooks work in the React Engine.

How Hooks Works

If we broke some rules, React Engine will give us a warning.

There are some basic hooks already build in the React Package. I will give an example for each Hooks using my project this semester.

  • useState
    This hooks is used to handle a single state value. It returns a list that contain state value and update function.
useState for handle a list
setCards for store the new value
  • useEffect
    This hooks is used to imitate life-cycle function in class-based component. There are two parameter, a function that want to be executed and dependencies. useEffect will execute the function if and only if there are any changes in the dependencies or in the first time component render. You can make an algorithm to filter which code will be executed each function call using condition inside the useEffect Hooks.
This useEffect will run the function only once because there are zero dependencies
This useEffect will run each time when the timeout variable greater than zero

Another feature from React Hooks, we can create new custom Hooks using existing Hooks and then encapsulate it using a function with “useXXX” as the function name. In my project in this semester, i use some custom Hooks to make my project code more cleaner.

  • useFormInput
    This hooks will create a state for HTMLInput and callback function to handle value change in HTMLInput.
  • useFetch
    This hook is used to fetch data from back-end server using AJAX. It will provide the response value, error value, and done status.

There are many more Hooks you can create by composing many hooks exist in React, you can see all the hooks in my reference.