React Hooks revolutionized the way we manage state and side effects in our React applications by allowing us to use state and other React features without writing a class. In this post, we'll delve into the two most frequently used Hooks: useState and useEffect.
The useState
Hook is the most basic Hook that allows you to add React state to functional components.
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 is called with the initial state, returning an array with the current state (count) and a function to update it (setCount).
useEffect lets you perform side effects in function components. Side effects could be anything that interacts with the world outside of the component, like data fetching, subscriptions, or manual DOM manipulations.
import React, { useState, useEffect } from 'react';
function UserComponent({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
const fetchUser = async () => {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
setUser(userData);
};
fetchUser();
}, [userId]);
return (
<div>{user ? `User name: ${user.name}` : "Loading..."}</div>
);
}
In the above example, useEffect runs after every render when the userId prop changes, fetching the user data for the given ID. The user state is then updated with the fetched data.
In conclusion, useState and useEffect are powerful Hooks that let you add state and manage side effects in function components in React. They allow for cleaner and more readable components by encapsulating the stateful logic inside these components. Understanding these Hooks is essential to mastering modern React development.