- Introduction
Today, we’re going to learn about React Hooks. Hooks are a way to use state and other React features in functional components, making them more powerful and easier to work with. Let’s dive into a conversation between Geek and Gal to explore React Hooks!
React Hooks are a game-changer for functional components in React!
How do Hooks work, and why are they important?
Hooks let you use state and lifecycle features in functional components, making them more flexible and easier to maintain. The most common hooks are
useState
and
useEffect
.
The
useState
hook allows you to add state to functional components. It returns an array with two elements: the current state value and a function to update it.
Can you show me an example?
Of course! Here's a simple example using
useState
in a functional component:
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>
);
}
I see! We use
useState
to add state to the functional component, and it returns the current state value and an update function.
That's right! It makes functional components more powerful and easier to work with.
The
useEffect
hook lets you perform side effects in functional components, like fetching data or updating the DOM. It's similar to the lifecycle methods in class components.
Can you show me an example of
useEffect
?
Sure! Here's an example of fetching data with
useEffect
in a functional component:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
}
fetchData();
}, []);
return (
<div>
{data.map((item) => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
I see!
useEffect
allows us to perform side effects in functional components, making them even more powerful!
Exactly! With hooks like
useState
and
useEffect
, functional components have become more versatile and easier to maintain.
How about a funny example using React Hooks?
Sure! Let's create a functional component that displays a random joke using hooks!
import React, { useState, useEffect } from 'react';
function RandomJoke() {
const [joke, setJoke] = useState('');
useEffect(() => {
async function fetchJoke() {
const response = await fetch('https://api.example.com/random-joke');
const data = await response.json();
setJoke(data.joke);
}
fetchJoke