5 Top Most Commonly Used React Hooks — For Beginners
Hamza Siddique
MERN Stack Developer @ Desol Int. | AWS | React.js | React Native (Expo) | Next.js | Node.js | Express.js | Nest.js | TypeScript | MERN Stack | Tailwind CSS | GraphQL | Docker (DevOps) | Angular | MEAN Stack
In this blog, we will understand the logic and uses of the top 5 React Hooks which are commonly used in React.js or Next.js applications.
Hooks are a powerful new feature introduced in React 16.8 that allows you to use state and other React features without writing a class. They let you “hook into” React state and lifecycle features from function components. This makes it possible to write simpler and more maintainable components.
Now we will discuss the top 5 hooks with their details and uses.
1. useState( )
useState() hook is used to add a state variable in your component which is used to update the state after the component is rendered. This hook can be used in the following scenarios.
import { useState } from 'react';
const [count, setCount] = useState(0)
Here we can break down the upper line of code.
Here following is the example of a counter using useState() in React.js
import { useState } from 'react';
function Counter() {
// Define state for the counter
const [count, setCount] = useState(0);
// Function to increment the counter
const increment = () => {
setCount(count + 1);
};
// Function to decrement the counter
const decrement = () => {
setCount(count - 1);
};
return (
<div>
<h2>Counter</h2>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
This component maintains a state variable count using the useState hook, initialized to 0. It renders the current value of count, along with buttons to increment and decrement the counter. The increment and decrement functions modify the state by calling setCount with the updated value.
2. useEffect()
The useEffect() hook is a powerful tool in React's arsenal for managing side effects within functional components. Side effects are actions that modify the DOM, perform network requests, or interact with external systems outside React's component lifecycle. The following are some scenarios where we can use this hook.
import { useEffect } from "react";
useEffect(){() => {
....
// Logical code here
...
},
return () => {
...
// clean up state logic
...
}
[]}
Here we can break down the upper useEffect() code.
There are 3 concepts about dependency array
useEffect(){() => {
....
// Logical code here
...
}, [count]}
In this case, if count state changes then useEffect() will run again.
3. useRef()
It is a React Hook that lets you reference a value that’s not needed for rendering. It returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. Following are some scenarios where we can use this hook.
import { useRef } from "react";
const ref = useRef(null)
Here we can break down the upper useRef() code:
Following is a basic example of useRef() using the input field:
领英推荐
import { useRef, useEffect } from 'react';
function MyComponent() {
const inputRef = useRef(null);
useEffect(() => {
// Focus on the input field when the component mounts
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
}
In this example, useRef is used to create a ref object (inputRef). This ref is then attached to an <input> element. Later, in the useEffect hook, the .focus() the method is called on inputRef.current, focusing on the input field when the component mounts.
4. useCallback()
It is a React Hook that helps improve performance by memoizing callback functions. In simpler terms, it caches a function and only returns a new version if its dependencies change. This prevents unnecessary re-renders of components that rely on that function. Following are some scenarios where we can use it.
import { useCallback } from "react";
const cachedFn = useCallback(()=> {
...
// your logical code
...
}, [])
Here we can break down the upper code of useCallback()
Following are the benefits of using useCallback() Hook:
Following is the basic example of useCallback():
import React, { useState, useCallback } from 'react';
const Button = ({ onClick, children }) => {
console.log("Button component rendered");
return <button onClick={onClick}>{children}</button>;
};
const App = () => {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []);
return (
<div>
<h1>Count: {count}</h1>
<Button onClick={increment}>Increment</Button>
</div>
);
};
export default App;
In this example:
5. useMemo()
It is a React Hook that helps you cache the result of an expensive calculation between re-renders. In simpler terms, it remembers a value so you don’t have to calculate it again and again, which can improve the performance of your React application. Following are some scenarios where we can use useMemo()
import { useMemo } from "react";
const cachedValue = useMemo(calculateValue, [])
Here we can break down the upper code of useMemo() Hook:
Following are the benefits of using useMemo() Hook:
Following is the basic example of useMemo()
import React, { useState, useMemo } from 'react';
const ExpensiveComponent = ({ data }) => {
// A function that does some heavy computation based on the data
const processData = (data) => {
// Just a placeholder heavy computation
console.log("Processing data...");
return data.map(item => item * 2);
};
// Use useMemo to memoize the result of processData function
const processedData = useMemo(() => processData(data), [data]);
return (
<div>
<h2>Expensive Component</h2>
<p>Processed Data: {processedData.join(', ')}</p>
</div>
);
};
const App = () => {
const [data, setData] = useState([1, 2, 3, 4, 5]);
const updateData = () => {
setData(prevData => [...prevData, prevData.length + 1]);
};
return (
<div>
<button onClick={updateData}>Update Data</button>
<ExpensiveComponent data={data} />
</div>
);
};
export default App;
In this example:
Conclusion
In conclusion, React hooks have transformed how developers manage state and lifecycle in React applications. They offer a cleaner, more concise approach to writing components by encapsulating logic and promoting functional programming principles.
Despite a learning curve for those accustomed to class-based components, embracing hooks brings efficiency and scalability to projects. Mastering hooks is essential for staying current in modern web development.
So, explore, experiment, and unlock the full potential of React hooks to enhance your projects and streamline your development process.
Happy coding!
Ex-SWE fellow @Headstarter AI | Web Developer | Next.js | React.js | Student @Gargi College
9 个月It was a great read. Thank you so much
Biochemistry PhD Candidate || Passionate Educator || Front-End Developer || WordPress Web Developer || AI Enthusiast
1 年An easy read. Thanks for this sir ??
Great insights for newcomers to React—understanding these hooks is definitely a game-changer for efficient coding!