Do you Know? What is Hooks, When and where to use Hooks? , the basic React Hooks that are available in the React, How to Write your own React Hooks? In this blog, We are going to discuss all about Hooks in deep. So Let's get started.
What Are React Hooks?
Hooks are newly added in React 16.8. React Hooks API provides an alternative to class-Based-Component, Hooks are in-built functions that allow React developers to use state and lifecycle methods inside functional components. we can work with React local state, Side-effects, and context through useState, useEffect, and useContext. Hooks are backward-compatible, which means it does not contain any breaking changes.
Rules of Hook
Hooks are just like JavaScript Functions, Before using or creating hooks we need to follow a few rules.
Hooks should be called at the top level of our component. Do not call Hooks inside loops, conditions, or nested functions.
Hooks should always be called from React Component, we cannot call Hooks from a regular javascript function.
UseState Hook
As we know, Inside the functional component, we do not have any local state. For adding a state, we can call useState inside a functional component and add a local State. whenever the render happens, useState returns two values, the current value, and a function that is used to update the current value. we can call this function from an event handler or somewhere else.
How to use UseState
- Import UseState Hook from React.
import { useState } from 'react';
- As we know that useState returns a pair, where the first one is a current value or initial value and the second one is a function, which allows us to update the current or initial value. Whenever we want to use it, we have to destructure the current value or initial value and function from the useState.
const [count, setCount] = useState(0);
Let's take an example, How we can create a counter using the useState.
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</>
);
}
In the above example, we have a button, As soon as the button is clicked, it will call the useState function and update the current value by 1.
UseEffect Hook
useEffect allows us to perform side effects in functional components, like updating the DOM, fetching data from Server and setting timers, etc. useEffect accepts two arguments. The first one is function and the other one is Dependency, we can skip the dependency as it is optional.
There are several ways we can pass Dependency.
- If we do not pass any dependency, useEffect runs on every render.
useEffect(() => {
//Runs on every render
});
- If we pass an empty array, useEffect runs only on the first render.
useEffect(() => {
//Runs only on the first render
});
- If we want to run useEffect which is dependent on a variable or a state change.
useEffect(() => {
//Runs on the first render
//Runs when the state change.
},[state]);
Let's take an example, How we can update the title using useEffect.
import { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
},[count]);
return (
<>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</>
);
}
In the above example, we have passed count dependency to the useEffect, As soon as the count will change, UseEffect will run and update the title.
useContext
Now, You are comfortable with hooks and how they work, So it's time to create your own custom Hooks. Custom hooks are normal javascript functions that can use other hooks inside of it. Why do we need a custom Hook? Using the Custom Hook we can access the global data and re-render when the global data is changed. Using custom Hook we can pass the data from a grandparent to a child without passing it to the parent.
Steps to create your own Custom Hook.
- Import createContext and initialize it.
import { useState, createContext } from "react";
const CounterContext = createContext()
- Wrap child components in the Context provide.
export function CounterProvider({ children }) {
const [count, setCounter] = useState(0);
return (
<CounterContext.Provider value={{ count, setCounter }}>
{children}
</CounterContext.Provider>
);
}
- Import the useContext and then pass CounterContext to useContext
import { useState, createContext,useContext} from "react";
const useCounter = () => useContext(CounterContext)
Let's see how we can create a custom context and use it.
- How you can create a custom Hook.
import { createContext, useContext, useState } from "react";
const CounterContext = createContext();
export function CounterProvider({ children }) {
const [count, setCounter] = useState(0);
return (
<CounterContext.Provider value={{ count, setCounter }}>
{children}
</CounterContext.Provider>
);
}
export const useCounter = () => useContext(CounterContext);
- How you can provide a custom hook to the app.
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { CounterProvider } from "./CounterContext";
import App from "./App";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<CounterProvider>
<App />
</CounterProvider>
</StrictMode>
);
- How you can use Custom Hook.
import "./styles.css";
import { useCounter } from "./CounterContext";
export default function App() {
const { count, setCounter } = useCounter();
return (
<div className="App">
<h1>{count}</h1>
<button onClick={() => setCounter(count + 1)}>Click me</button>
</div>
);
}
Conclusion
Now, You have a good understanding of how you can use hooks in functional components and create your own hooks. There are other hooks like useReducer, useMemo, useCallback, etc. We will cover this in the next blog. Hope you liked this blog.
Do share your feedback in the comments and help me to improve.
ThankYou.