React Hooks: A Complete Beginner's Guide
React Hooks are a way to add functionality to functional components in React. Before hooks, we had to use class components to manage state or perform side effects. Hooks make it easier and cleaner to write React code. Let's dive into the basics!
Basic Hooks
1. useState
What is it? useState
allows us to create state variables in functional components. Think of state as a "memory" for your component that allows it to "remember" information, like user inputs or the current score in a game.
Real-Life Example: Imagine you're building a simple counter app. The number you see on the screen is the "state" of the app, and you can change it when you click the button.
Code Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // count is the state, setCount is the function to change it
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
2. useEffect
What is it? useEffect
is used to handle side effects like fetching data, updating the DOM, or subscribing to events. It's like telling your app to "do something" after it finishes rendering the page.
Real-Life Example: Imagine you're building a weather app. You need to fetch the weather data after the app loads, so you use useEffect
to run that logic after rendering.
Code Example:
import React, { useState, useEffect } from 'react';
function Weather() {
const [weather, setWeather] = useState(null);
useEffect(() => {
fetch('https://api.example.com/weather')
.then(response => response.json())
.then(data => setWeather(data));
}, []); // The empty array means this effect only runs once, after the first render
return <div>{weather ? `Today's temperature: ${weather.temp}` : 'Loading...'}</div>;
}
3. useContext
What is it? useContext
allows you to use values (like themes or user information) from a global context directly in your component. It’s like a "global storage" that your components can access without passing props down manually.
Real-Life Example: Imagine you have an app with a dark mode setting. Instead of passing the dark mode state through each component, you can use useContext
to access it globally.
Code Example:
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedComponent() {
const theme = useContext(ThemeContext);
return <div>The current theme is {theme}.</div>;
}
Conclusion
These basic hooks—useState
, useEffect
, and useContext
—are essential for building dynamic, interactive apps with React. They let you manage data, perform side effects, and share information across components efficiently.
Comments
Post a Comment