React Hooks were introduced in React 16.8 that allows you enhance your react functional components in multiple ways. They were introduced to make it easier to manage state and side-effects in functional components, and also to make it easier to share logic between components.
In this article i will be covering the most popular react hook with their usage and examples:
1. useState
The useState hook allows you to add state to a functional component. It takes an initial value as an argument and returns an array with two elements: the current state and a function to update it.
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</>
);
}
2. useEffect
The useEffect hook allows you to run side-effects in a functional component, such as fetching data or updating the document title. It takes a callback function as an argument and runs it after the component has rendered.
import { useEffect } from 'react';
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return <p>Data: {JSON.stringify(data)}</p>;
}
3. useContext
The useContext hook allows you to access the context in a functional component. It takes the context object as an argument and returns the current context value.
import { useContext } from 'react';
const MyContext = React.createContext(defaultValue);
function Example() {
const context = useContext(MyContext);
return <p>Context value: {context}</p>;
}
4. useReducer
The useReducer hook allows you to handle state updates with a reducer function in a functional component. It takes a reducer function and an initial state as arguments and returns the current state and a dispatch function.
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Example() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>
+
</button>
<button onClick={() => dispatch({ type: 'decrement' })}>
-
</button>
</>
);
}
5. useCallback
The useCallback hook returns a memoized callback that only changes if one of its dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
import { useCallback } from 'react';
function Example({ onClick }) {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
onClick();
}, [count, onClick]);
return (
<>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
</>
);
}
Here, handleClick
will only change if count
or onClick
changes, which means that the component using this callback will not re-render unless one of those values change.
Wrapping Up
In conclusion, React Hooks have greatly simplified the way we handle state and side-effects in functional components. By understanding and utilizing the most popular hooks, such as useState, useEffect, useContext, useReducer, and useCallback, you can create clean, efficient, and maintainable code.
With useState, you can easily add state to your functional components. useEffect lets you handle side-effects, such as data fetching and updates to the document title. useContext allows you to access context in functional components, making it easy to share data across your application. useReducer allows you to handle state updates with a reducer function, and useCallback returns a memoized callback that only changes if its dependencies have changed, which is useful for optimizing child components.
React Hooks have become a powerful tool for building dynamic and performant applications, allowing developers to write clear and concise code that is easy to understand, maintain and test. As you continue to work with React, mastering these hooks will be essential to creating high-quality user interfaces.
About Zafar Kamal
Get in TouchI'm a full-stack developer with expertise in React, Node, and PHP WordPress. I have 4+ year of experience in working with clients from all over the world, providing fully responsive front-end development, WordPress plugin development. I'm also highly familiar with WordPress native editor (Gutenberg API) and can create custom Gutenberg Blocks.