Welcome to our beta testing phase! Your feedback is invaluable as we work to enhance your experience. Give us your Feedback here!
Get the latest insights, articles, and coding tips delivered straight to your inbox. Subscribe now to stay informed and boost your coding skills.
Posted By Coding_Dynasty 4 months ago
Reading Time: 3 Minutes
React Functional Components with Hooks introduced in React 16.8 provide a concise and powerful way to manage state and lifecycle events in functional components. Hooks like
useState
,useEffect
, and others enhance the capabilities of functional components, making them more versatile. Here's an overview of using functional components with hooks:
1. useState Hook:
useState
allows functional components to manage state:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
2. useEffect Hook:
useEffect
enables performing side effects in functional components:
import React, { useState, useEffect } from 'react';
const DataFetcher = () => {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch data when the component mounts
fetchData();
}, []); // Empty dependency array ensures it runs only once
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
}
};
return (
<div>
<h2>Fetched Data</h2>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
3. useContext Hook:
useContext
simplifies accessing context values in functional components:
import React, { useContext } from 'react';
import MyContext from './MyContext';
const DisplayContextValue = () => {
const contextValue = useContext(MyContext);
return <p>Context Value: {contextValue}</p>;
};
4. useReducer Hook:
useReducer
is useful for managing more complex state logic:
import React, { useReducer } from 'react';
const counterReducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};
const CounterWithReducer = () => {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
};
5. Custom Hooks:
Create custom hooks to reuse stateful logic across components:
import { useState, useEffect } from 'react';
const useDataFetching = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading };
};
// Usage in a component
const DataFetcher = () => {
const { data, loading } = useDataFetching('https://api.example.com/data');
return (
<div>
{loading ? (
<p>Loading...</p>
) : (
<div>
<h2>Fetched Data</h2>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)}
</div>
);
};
React Functional Components with Hooks offer a modern and concise way to manage state and lifecycle events in React applications. Whether you're handling simple component state or complex data fetching logic, hooks empower you to write cleaner and more maintainable code. Explore the wide range of hooks provided by React to streamline your component logic and enhance your development workflow.