What are React Hooks?
Hooks are the new feature in the React. React Hooks accept to use the features of class-based components in Function-based Components.
Hooks is a collection of new functions that lets you create stateful components without writing classes and with just using functions in react.
Why do we need to learn React Hooks?
Most common hooks in react are used useState, useEffect, useContext, useRef etc.
We can easily create const variables and can update its value by using useState.
By using useEffect hook we can render anything while on page loading and even you can add dependencies so there you can declare when to run the function if some value or state changes.
Commonly used React Hooks :
- useState
- useEffect
- useContext
- useRef
useState:-
useState is a react hook. This hook is a very common hook in react which is used to store and update any variable value on a component level.
Declaring state in React
useState is a named export from react. To use it, you can write:
React.useState
Or to import it just write useState:
import React, { useState } from 'react';
useEffect:-
useEffect Hook used to perform side effects in your components.
useEffect Hook works similarly to adding a function on componentDidMount and componentDidUpdate.
useEffect takes two arguments.and second argument is optional. useEffect(<function>, <dependency>)
useContext:-
useContext provides a way to pass data through the component tree without having to pass props down manually at every level in react.
Context allows to share values between components without having to explicitly pass a props through every level of the tree.
If some data needs to be accessible by many components at different nesting levels so we use useContext.
useRef:-
useRef hooks is one of the standard hooks provided by react that returns a mutable ref object whose .current property is initialized with the passed argument (initialValue).
const refContainer = useRef(initialValue);
useRef returns a “ref” object in react and useRef Hook allows you to persist values between renders.
useReducer:-
useReducer hook is used for handling complex states and transitions in state and useReducer Hook accepts two arguments. This hook allows for custom state logic. It takes in a reducer function and also an initial state input; then, it returns the current state and also a dispatch function as output by the means of array destructuring.
The proper syntax of useReducer hook.
const [state, dispatch] = useReducer(reducer, initialArg, init);
Other Hooks Available in React #
useCallback | useCallback hook returns a callback function that is memoized and that only changes if one dependency in the dependency tree changes in react. |
useMemo | useMemo hook returns a memoized value, you can pass in a “create” function and also an array of dependencies. The value it returns will only use the memoized value again if one of the dependencies in the dependency tree changes in react. |
useImperativeHandle | useImperativeHande hook is used for customizing the instance value that is made available for parent components when using refs in React. |
useLayoutEffect | useLayoutEffect hook is similar to the useEffect hook, however, it fires synchronously after all DOM mutations. It also renders in the same way as class components, componentDidUpdate and componentDidMount. |
useDebugValue | useDebugValue hook can be used to display a label for custom hooks in the React Dev Tools. It is very useful for debugging with the React Dev Tools in react. |
Custom React Hooks #
“Custom Hook” is a JavaScript function for Building your own Hooks whose names are prefixed with the word use and can be used to call other Hooks. It also lets you extract component logic into reusable functions; they are normal JavaScript functions that can make use of other Hooks inside of it, and also contain a common stateful logic that can be made use of within multiple components.
The code snippets below demonstrate an example of a custom React :
import { useState } from "react";
export const useInfiniteScroll = (start = 30, pace = 10) => {
const [limit, setLimit] = useState(start);
window.onscroll = () => {
if (
window.innerHeight + document.documentElement.scrollTop===
document.documentElement.offsetHeight
) {
setLimit(limit + pace);
}
};
return limit;
};
Custom Hook accepts two arguments: start and pace. The start argument is the starting number of elements to be rendered while the pace argument is the subsequent number of elements that are to be rendered. By default, the start and pace arguments are set to 30 and 10 respectively which means you can actually call the Hook without any arguments and those default values will be used instead.
So in order to use this Hook within a React app, we would use it with an online API that returns ‘fake’ data:
import React, { useState, useEffect } from "react";
import { useInfiniteScroll } from "./useInfiniteScroll";
const App = () => {
let infiniteScroll = useInfiniteScroll();
const [tableContent, setTableContent] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos/")
.then(response => response.json())
.then(json => setTableContent(json));
}, []);
return (
<div style={{ textAlign: "center" }}>
<table>
<thead>
<tr>
<th>User ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{tableContent.slice(0, infiniteScroll).map(content => {
return (
<tr key={content.id}>
<td style={{ paddingTop: "10px" }}>{content.userId}</td>
<td style={{ paddingTop: "10px" }}>{content.title}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default App;
Conclusion #
Hooks is a collection of new functions that lets you create stateful components without writing classes and with just using functions in react.
Benefits of Using React Hooks provides three benefits:
- Reusability
- Readability
- Testability.