React Hooks are a feature introduced in React version 16.8 to provide a way to use state and other React features in functional components, without the need to write class components. Before React Hooks, stateful logic could only be handled within class components using state
and lifecycle methods.
Hooks allow you to use state and other React features like context, effect, and memoization directly in functional components. They promote the reusability of stateful logic, making it easier to manage and share between components.
Some of the most commonly used React Hooks are:
1.useState
: Allows functional components to have state by providing a state variable and a function to update it. For example:
import React, { useState } from 'react'; const ExampleComponent = () => { const [count, setCount] = useState(0); const increment = () => setCount(count + 1); return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); };
2.useEffect
: Lets you perform side effects in functional components, such as fetching data from an API, subscribing to events, etc. It runs after the component has rendered. For example:
import React, { useState, useEffect } from 'react'; const ExampleComponent = () => { const [data, setData] = useState([]); useEffect(() => { // Fetch data from an API and update the state fetch('https://api.example.com/data') .then((response) => response.json()) .then((data) => setData(data)); }, []); return ( <div> {data.map((item) => ( <p key={item.id}>{item.name}</p> ))} </div> ); };
3.useContext
: Allows you to consume the nearest context value from a provider in a functional component. For example:
import React, { useContext } from 'react'; const MyContext = React.createContext(); const ExampleComponent = () => { const value = useContext(MyContext); return <p>{value}</p>; };
React Hooks make it easier to create and maintain functional components with state and other React features, promoting a more concise and readable codebase compared to using class components. They have become widely adopted and are an essential part of modern React development.