React Hooks
React Hooks are a feature introduced in React 16.8. They provide a way to use state and other React features in functional components, without the need for class components and lifecycle methods.
useState
The useState
hook allows us to add state to functional components. It returns an array with two elements: the current state value and a function to update the state. Here's an example:
1const [count, setCount] = useState(0);
In this example, we're using the useState
hook to add a count
state to our component. The initial value of count
is 0, and the setCount
function is used to update the state value.
useEffect
The useEffect
hook allows us to perform side effects in functional components. It's similar to the componentDidMount
, componentDidUpdate
, and componentWillUnmount
lifecycle methods of class components.
The useEffect
hook takes two arguments: a callback function that performs the side effect and an optional array of dependencies. The callback function is executed after the component renders, and it can return a cleanup function that will be called when the component unmounts.
Here's an example of using the useEffect
hook:
1useEffect(() => {
2 // This function is called after every render
3 console.log('Component mounted');
4
5 // Return a cleanup function
6 return () => {
7 console.log('Component unmounted');
8 };
9}, []);
In this example, the useEffect
hook is used to log a message when the component mounts and unmounts. The empty array []
as the second argument ensures that the effect only runs once, similar to componentDidMount
.
React Hooks provide a more concise and flexible way to work with state and side effects in functional components. They have become the recommended approach for writing React components.
xxxxxxxxxx
export default ExampleComponent;
// Replace with relevant React Hooks code
import React, { useState, useEffect } from 'react';
const ExampleComponent = () => {
const [count, setCount] = useState(0);
useEffect(() => {
// Replace with side effect code
console.log('Component mounted');
return () => {
// Replace with cleanup code
console.log('Component unmounted');
};
}, []);
const handleIncrement = () => {
setCount(count + 1);
};
const handleDecrement = () => {
setCount(count - 1);
};
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={handleIncrement}>Increment</button>