2024-06-07 . 2 min(s)

Introduction to React Hooks

intro to react hooks screenshot

React Hooks are functions that let you use state and other React features in functional components. Introduced in React 16.8, hooks have become an essential part of modern React development.

useState Hook

The useState hook allows you to add state to functional components.

Example:

import React, { useState } from 'react';

const Counter = () => {
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
};

export default Counter;

useEffect Hook

The useEffect hook lets you perform side effects in functional components. It's similar to lifecycle methods in class components.

Example:

import React, { useEffect, useState } from 'react';

const DataFetcher = () => {
const [data, setData] = useState(null);

useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []); // Empty dependency array means this effect runs once after the initial render

return (
<div>
{data ? <p>Data: {data.message}</p> : <p>Loading...</p>}
</div>
);
};

export default DataFetcher;

Custom Hooks

You can create custom hooks to encapsulate reusable logic.

Example:

import { useState, useEffect } from 'react';

const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => {
console.error('Error fetching data:', error);
setLoading(false);
});
}, [url]);

return { data, loading };
};

export default useFetch;

Hooks make your components cleaner and more modular, promoting code reuse and better organization.