React Hooks have transformed the way we write components in React. Today, we'll explore two of the most commonly used hooks: useState and useEffect.
useState: Managing State in Functional Components
The useState hook allows you to add state to functional components. Here's a simple example:
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>
);
}
In this example, useState gives us a state variable (count) and a function to update it (setCount). The initial state is set to 0.
useEffect: Side Effects in Components
The useEffect hook lets you perform side effects in functional components. It's like componentDidMount, componentDidUpdate, and componentWillUnmount combined.
jsxCopyimport React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In this example, useEffect updates the document title every time the count changes.
Conclusion
These hooks make it easier to use state and lifecycle features without classes. They're just the tip of the iceberg - React offers many more hooks to explore!
Happy coding, and may your components be ever functional!