React Hooks Explanation in 150 Words!

React hook is a new extension to react version 16.8 that allows you to use state and other lifecycle methods within a function-based component. In other words, now React developers can use things like State within their function components in addition to having more control over the lifecycle of these components.

Hooks & Reusable Functions

Moreover, the hooks allow us to break out functionality into reusable functions. If you are unfamiliar with reusable functions, I can put it in this way; you could almost think about this as the same way that we could break out UI elements into components we can break out actual functionality into reusable functions (i.e., hooks) that we can throw inside of our function-based components.

A Simple Example of React Hooks Application?

For example, it allows us to create a custom hook that determines if a click occurs inside of a div or not or a custom hook that allows us to easily access local storage via a simple function.

A Sample Code with React Hooks


     import { useEffect, useReducer } from "react";

const initialState = {
  loading: "",
  error: "",
  data: []
};

function apiReducer(state, action) {
  switch (action.type) {
    case "DATA_FETCH_START":
      return { ...state, loading: "yes" };
    case "DATA_FETCH_FAILURE":
      return { ...state, loading: "", error: action.payload };
    case "DATA_FETCH_SUCCESS":
      return { ...state, loading: "", data: action.payload };
    default:
      return state;
  }
}

export function useFetch(endpoint) {
  const [data, dispatch] = useReducer(apiReducer, initialState);

  useEffect(() => {
    dispatch({ type: "DATA_FETCH_START" });

    fetch(endpoint)
      .then(response => {
        if (!response.ok) throw Error(response.statusText);
        return response.json();
      })
      .then(json => {
        dispatch({ type: "DATA_FETCH_SUCCESS", payload: json });
      })
      .catch(error => {
        dispatch({ type: "DATA_FETCH_FAILURE", payload: error.message });
      });
  }, []);

  return data;
}

   		  

References

Posted by Mohammadreza in April 2021

I'm a cybersecurity researcher and a full-stack developer.