Introduction
In this blog post, we will explore React Hooks – a new addition to React that allows functions to use state and other React features. This feature was introduced with the release of React 16.8, and it simplifies the way we manage state in functional components.
Before Hooks
Before Hooks, managing state in functional components was not possible. This limitation forced developers to create class components for handling state. Although class components served their purpose, they were more complex and less flexible than functional components.
Enter React Hooks
React Hooks introduce a way to use state and other React features in functional components. This means we can now write functional components that can handle state, lifecycle methods, and more. The most commonly used Hooks are `useState` and `useEffect`.
Using useState Hook
The `useState` Hook lets you add React state to functional components. Here’s an example of a simple component using `useState`:
“`jsx
import React, { useState } from ‘react’;
function Example() {
const [count, setCount] = useState(0);
return (
You clicked {count} times
);
}
“`
In this example, the `useState` Hook is used to create a state variable called `count` and a function `setCount` to update it. The button’s click event increments the count.
Using useEffect Hook
The `useEffect` Hook lets you perform side effects in function components. For example, you can fetch data or manually change the DOM. Here’s an example:
“`jsx
import React, { useState, useEffect } from ‘react’;
function Example() {
const [count, setCount] = useState(0);
const [name, setName] = useState(”);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
You clicked {count} times
setName(e.target.value)} />
);
}
“`
In this example, the `useEffect` Hook updates the document title whenever the `count` state changes.
Conclusion
React Hooks have made it possible to manage state in functional components, making our code cleaner and more flexible. With Hooks, we can write simpler components that are easier to understand and maintain.