React - Custom Hooks
Creating and using custom hooks
Custom hooks are a powerful feature in React that allow you to extract and reuse logic in your components. A custom hook is a JavaScript function that starts with "use" and can call other hooks. Custom hooks help you to write cleaner, more modular code by sharing logic between components. This tutorial covers how to create and use custom hooks in React.
Key Points:
- Custom hooks are JavaScript functions that start with "use".
- They can call other hooks and share logic between components.
- Custom hooks help you write cleaner, more modular code.
- They follow the same rules as regular hooks, such as only calling hooks at the top level.
Basic Example
Here is a basic example of a custom hook that manages a counter:
// Creating a custom hook
import React, { useState } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
}
// Using the custom hook in a component
function Counter() {
const { count, increment, decrement, reset } = useCounter(10);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default Counter;
Fetching Data with Custom Hooks
Custom hooks can be used to encapsulate data fetching logic. Here is an example of a custom hook that fetches data from an API:
// Creating a custom hook for data fetching
import React, { useState, useEffect } from 'react';
function 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);
});
}, [url]);
return { data, loading };
}
// Using the custom hook in a component
function DataFetcher({ url }) {
const { data, loading } = useFetch(url);
return (
<div>
{loading ? <p>Loading...</p> : <p>Data: {JSON.stringify(data)}</p>}
</div>
);
}
export default DataFetcher;
Managing Forms with Custom Hooks
Custom hooks can also be used to manage form state. Here is an example of a custom hook that handles form input:
// Creating a custom hook for form management
import React, { useState } from 'react';
function useForm(initialValues) {
const [values, setValues] = useState(initialValues);
const handleChange = (event) => {
const { name, value } = event.target;
setValues({ ...values, [name]: value });
};
const reset = () => setValues(initialValues);
return { values, handleChange, reset };
}
// Using the custom hook in a component
function LoginForm() {
const { values, handleChange, reset } = useForm({ username: '', password: '' });
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted:', values);
reset();
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input type="text" name="username" value={values.username} onChange={handleChange} />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" value={values.password} onChange={handleChange} />
</div>
<button type="submit">Login</button>
</form>
);
}
export default LoginForm;
Reusing Logic with Custom Hooks
Custom hooks allow you to reuse logic across multiple components. Here is an example of a custom hook that tracks the window width:
// Creating a custom hook for window width
import React, { useState, useEffect } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
// Using the custom hook in a component
function WindowWidth() {
const width = useWindowWidth();
return <p>Window width: {width}</p>;
}
export default WindowWidth;
Summary
In this tutorial, you learned how to create and use custom hooks in React. Custom hooks are JavaScript functions that start with "use" and can call other hooks. They allow you to extract and reuse logic in your components, making your code cleaner and more modular. You learned about creating basic custom hooks, fetching data with custom hooks, managing forms with custom hooks, and reusing logic with custom hooks. Understanding custom hooks is essential for writing reusable and maintainable React code.