There are several built-in hooks, but two fundamental ones are useState
and useEffect
.
-
useState:
useState
is used to add state to functional components.- It returns an array with two elements: the current state value and a function that lets you update it.
- Here's a simple example:
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example, count
is the state variable, and setCount
is the function to update it. When the button is clicked, the setCount
function is called to increment the count.
-
useEffect:
useEffect
is used for side effects in your components, such as fetching data, subscribing to external events, or updating the DOM.- It takes two arguments: a function to run the effect and an optional array of dependencies.
import React, { useState, useEffect } from "react";
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
// This code runs after the component renders
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => setData(data));
}, []); // The empty array means this effect runs once when the component mounts
return <div>{data ? <p>Data: {data}</p> : <p>Loading...</p>}</div>;
}
In this example, the useEffect
fetches data when the component mounts. The empty array []
as the second argument ensures that the effect runs only once.
React Hooks simplify state management and side effects in functional components, making your code more readable and maintainable. They are a powerful tool for building dynamic and interactive user interfaces in React.
**
- useDarkMode: This hook manages the state for a dark mode toggle.
import { useState } from "react";
function useDarkMode() {
const [isDarkMode, setIsDarkMode] = useState(false);
const toggleDarkMode = () => {
setIsDarkMode((prevMode) => !prevMode);
};
return [isDarkMode, toggleDarkMode];
}
Usage:
function DarkModeToggle() {
const [isDarkMode, toggleDarkMode] = useDarkMode();
return (
<div>
<p>Dark Mode: {isDarkMode ? "On" : "Off"}</p>
<button onClick={toggleDarkMode}>Toggle Dark Mode</button>
</div>
);
}
In this example:
useDarkMode
initializes theisDarkMode
state tofalse
.- It provides a
toggleDarkMode
function to switch between dark and light modes. - The
DarkModeToggle
component uses this hook to manage and display the dark mode state. The simplicity lies in encapsulating the logic related to dark mode within the custom hook, making it easy to reuse in other components.
Remember, a custom hook is essentially a function that uses React's built-in hooks to manage state or perform side effects. It follows the naming convention useSomething
to signify that it's a hook. By creating custom hooks, you can abstract away complex logic and reuse it across your application.