React Hooks: Managing State and Lifecycle in Functional Components
Traditionally, managing state and lifecycle methods in React components was only possible in class components. However, with the introduction of React Hooks, we can now use state and lifecycle methods in functional components as well.
React Hooks are functions that allow us to use state and other React features without writing a class. They provide a simpler and more intuitive way to manage state and lifecycle in functional components.
One of the most commonly used React Hooks is the useState
Hook. It allows us to add state to our functional components. Here's an example:
JAVASCRIPT
1import React, { useState } from 'react';
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 return (
7 <div>
8 <p>Count: {count}</p>
9 <button onClick={() => setCount(count + 1)}>Increment</button>
10 </div>
11 );
12}