React Hooks

Shahariyer Ahammed
3 min readDec 29, 2021

Hooks are simply functions that allow us to add lifecycle features and states to functional components.

Rules of Hook

There are two rules that must be followed when working with Hooks
Hooks should always be called at the top level. Hooks should not be called inside loops, conditions, or nested functions. This is to ensure that after every render of the components, the Hooks are called in the same order every time.
Hooks can only be called from React functions. Hooks cannot be called from regular JavaScript functions. Therefore, they can be called from functional components and from custom Hooks.

Basic Hooks

useState

const [state, setState] = useState(initialState);

This hook is used to add states to functional components. Using the initialState argument, we can provide an initial state if needed. The hook returns the current state and a function that is used to update the state. If the state is updated, the component is re-rendered.

For naming the state and its updating function, the common convention that is followed is [something, setSomething].

useEffect
This hook is used to perform side functions in the components, such as fetching data, subscription set up etc. It is used to make the component do something right after rendering. It runs after every render by default.

useEffect(()=> {
// some code }, [])

The optional second argument is so that the component re-renders only if the value of that argument has changed.

useContext
This hook is useful in avoiding prop drilling as it allows to manage states globally. The components can be re-rendered when these global states change.

First, the context has to be created and initialized. Then the child components have to be wrapped in the Context Provider and the state value has to be supplied.

const UserContext = createContext()
function Component1() {
const [user, setUser] = useState("Jesse Hall");
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 user={user} />
</UserContext.Provider>
);
}

After this, the user Context will be accessible in all the components.

React Custom Hooks

Custom Hooks

The reusable function can be a Hook. When we create a logical function, that function can be used in multiple components. For that, we can extract out the logic to reuse. A hook function name starts with “use” example: “useFetch”

Usually, we need to fetch data in different components like this.

import { useState, useEffect } from "react";const Home = () => {
const [data, setData] = useState();
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
.then((res) => res.json())
.then((data) => setData(data));
}, []);
return (
<>
{data &&
data.map((item) => {
return <p key={item.id}>{item.title}</p>;
})}
</>
);
};
export default Home;

So now we can create a Hook for fetch logic as we can reuse it in other components. Like this,

import { useState, useEffect } from "react";const useFetch = (url) => {
const [data, setData] = useState();
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => setData(data));
}, [url]);
return [data];
};
export default useFetch;

Now we can fetch data with our custom Hook. as usual

import react from "react";
import useFetch from "./useFetch";
const Home = () => {
const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");
return (
<>
{data &&
data.map((item) => {
return <p key={item.id}>{item.title}</p>;
})}
</>
);
};
export default Home;

--

--