React hooks have revolutionized the way we write React components, providing a more intuitive API for managing state and side effects in functional components. Among the most commonly used hooks are useState and useEffect. In this post, we'll dive into these hooks, exploring their usage with practical examples.
The useState hook allows you to add state to functional components. It returns a stateful value and a function to update it. Here's a simple example to illustrate:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
In this example:
useState hook from React.useState(0) to declare a state variable count with an initial value of 0.setCount function to update the state when the button is clicked.The useEffect hook allows you to perform side effects in your components. Examples of side effects include data fetching, subscriptions, and manually changing the DOM.
Here's a basic example:
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div>
<p>Elapsed time: {seconds} seconds</p>
</div>
);
}
export default Timer;
In this example:
seconds state variable.useEffect to set up a timer that increments seconds every second.return () => clearInterval(interval)) ensures the timer is cleared when the component unmounts, preventing memory leaks.