Sharing stateful logic in React can be efficiently handled through the use of custom hooks. Custom hooks allow developers to encapsulate stateful logic and reuse it across multiple components, promoting cleaner code and better separation of concerns. This approach is particularly useful when you have logic that needs to be shared between different components without duplicating code.
To create a custom hook, you simply define a function that starts with the word "use" and can call other hooks within it. This function can return any values or functions that you want to share with the components that use this hook.
Here’s a practical example of a custom hook that manages a counter:
import { useState } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(c => c + 1);
const decrement = () => setCount(c => c - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
}
In this example, the `useCounter` hook manages a counter's state and provides functions to increment, decrement, and reset the counter. You can now use this hook in any component:
import React from 'react';
import useCounter from './useCounter';
function CounterComponent() {
const { count, increment, decrement, reset } = useCounter(0);
return (
Count: {count}
);
}
By following these guidelines, you can effectively share stateful logic across your React components using custom hooks, leading to more maintainable and reusable code.