Learn about the different types of React hooks with code examples
Aneh Thakur
. 2 min read
React hooks are a powerful feature that allows you to use state and other React features inside functional components. In this tutorial, you will learn about the different types of hooks available in React, and see code examples of how to use them in your own projects.
In React, a "hook" is a way to use state and other React features inside functional components. Hooks were introduced in React 16.8, and they have been a game-changer for the way that we build React applications.
Here are a few examples of common hooks in React:
useState
: This hook allows you to add state to a functional component. It returns an array with two elements: the current state value and a function to update the state.
import { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count"const [count, setCount] = useState(0); return ( <div><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}> Click me </button></div> ); }
useEffect
: This hook allows you to perform side effects in functional components. It takes a function as an argument, which will be called after the component renders.
import { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); // Similar to componentDidMount and componentDidUpdate:useEffect(() => { // Update the document title using the browser APIdocument.title = `You clicked ${count} times`; }); return ( <div><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}> Click me </button></div> ); }
useContext
: This hook allows you to access the value of a context object inside a functional component.
import { useContext } from 'react'; const MyContext = React.createContext(); function Example() { const value = useContext(MyContext); return ( <div>{value}</div> ); }
useReducer
: This hook is similar touseState
, but it allows you to manage complex state changes with a reducer function. It returns the current state value and a dispatch function, which you can use to update the state by calling the reducer with an action.
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 Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <> Count: {state.count} <button onClick={() => dispatch({ type: 'increment' })}>+</button><button onClick={() => dispatch({ type: 'decrement' })}>-</button></> ); }
useCallback
: This hook returns a memoized version of a callback function. It can be useful for optimizing performance when passing a callback to a component that uses theuseMemo
oruseEffect
hook.
import { useState, useCallback } from 'react'; function Parent() { const [value, setValue] = useState(0); const increment = useCallback(() => setValue(v => v + 1), [setValue]); return <Child increment={increment} />; } function Child({ increment }) { // The increment function will only be re-created if the// setValue dependency changesreturn <button onClick={increment}>Increment</button>; }
useMemo
: This hook returns a memoized value. It can be useful for optimizing performance by avoiding unnecessary re-computations.
import { useState, useMemo } from 'react'; function ExpensiveComponent() { const [count, setCount] = useState(0); // Only re-compute the result if count changesconst expensiveResult = useMemo(() => doExpensiveComputation(count), [count]); return ( <div><button onClick={() => setCount(count + 1)}>Increment</button><div>{expensiveResult}</div></div> ); }
I hope these examples help you understand how hooks can be used in React!.
More Stories from
Get Started with TypeScript: A Beginner's Guide with Code Samples
TypeScript is a popular, powerful programming language that is a superset of JavaScript. If you're new to TypeScript, this beginner's guide is the perfect place to start. With clear explanations and code samples, you'll learn the basics of TypeScript and
TypeScript vs TSX: Understanding the Differences
This article delves into the key differences between TypeScript and TSX, two programming languages used for developing complex web applications. From syntax and static typing to React integration and code organization, learn which language is best suited
A step-by-step guide to deploying a ReactJS app online
Learn how to deploy your ReactJS app to the internet with this comprehensive tutorial. From setting up a hosting platform to building and uploading your code, we'll cover all the steps you need to take to get your app live. Whether you're a beginner or an
What is React context API?
React Context is a way to share values that are considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. It allows you to avoid prop drilling, or the passing of props through multiple levels
All about MongoDB
MongoDB is an open-source document-oriented database that is designed to store a large scale of data and also allows you to work with that data very efficiently. It is categorized under the NoSQL (Not only SQL) database because the storage and retrieval o