Tutorial: React Hooks Explained
Understand and use React Hooks (`useState`, `useEffect`) to manage state and side effects in functional components.
By Upingi Team / Tutorial Level: Intermediate
Understand and use React Hooks (`useState`, `useEffect`) to manage state and side effects in functional components.
By Upingi Team / Tutorial Level: Intermediate
React Hooks allow you to use state and other React features in functional components, which were previously only available in class components. They make component logic more reusable and easier to understand.
Hooks like `useState` and `useEffect` are fundamental for building modern React applications.
Let's hook into React features!
The `useState` hook lets you add state variables to functional components.
You clicked { count } times
`.Build a simple counter component using `useState`.
The `useEffect` hook lets you perform side effects in functional components. Common side effects include data fetching, setting up subscriptions, and manually changing the DOM.
Basic Usage:
Import it alongside `useState`: `import React, { useState, useEffect } from 'react';`. Then, call `useEffect` inside your component, passing it a function (the "effect").
useEffect(() => {
// This code runs after every render
document.title = `You clicked ${count} times`;
}); // No dependency array: runs on every render
Controlling When Effects Run (Dependency Array):
The second argument to `useEffect` is the dependency array. It controls when the effect function re-runs:
useEffect(() => {
console.log('Count changed to:', count);
}, [count]); // Only re-run the effect if count changes
useEffect(() => {
// Fetch data only on initial render
fetchData();
}, []); // Empty array: runs only once
Cleanup Function:
If your effect sets up something that needs to be cleaned up (like a subscription or timer), you can return a function from your effect. React will run this cleanup function before the component unmounts or before the effect re-runs.
useEffect(() => {
const timerId = setInterval(() => {
console.log('Tick!');
}, 1000);
// Cleanup function
return () => {
clearInterval(timerId);
console.log('Timer cleared!');
};
}, []); // Run once, cleanup on unmount
You've learned the basics of `useState` for state management and the purpose of `useEffect` for side effects in React functional components. Hooks are essential tools for building modern React apps.
Explore more Hooks: