Open In App

How to handle side effects in a Custom Hook?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Handling side effects in a custom Hook involves managing actions or changes that occur outside of the primary function of the Hook itself. You can effectively handle side effects within your custom Hooks while keeping your code clean and maintainable.

Handling Side Effects In a Custom Hook:

  • Identify Side Effects: First, recognize what side effects your Hook might have. Side effects can include things like making network requests, changing browser history, or updating the DOM.
  • Use Built-in Hooks: Whenever possible, leverage built-in React Hooks i.e. useEffect to handle side effects. This allows you to keep your custom Hook clean and focused on its main purpose.
  • Encapsulate Side Effects: If your custom Hook needs to perform side effects, encapsulate them within the Hook itself. This means bundling any necessary side effect logic within the Hook’s implementation, keeping it self-contained and reusable.
  • Return Cleanup Functions: If your side effects require cleanup (like unsubscribing from event listeners), return a cleanup function from your custom Hook. This function will be called when the component using the Hook unmounts or when dependencies change.
  • Test Thoroughly: Finally, thoroughly test your custom Hook to ensure it behaves as expected, especially regarding its side effects. This includes testing different usage scenarios and edge cases.

Example: Below is an example of handling side effects in a custom hook.

Javascript




import React, {
    useState,
    useEffect
} from 'react';
 
const useLocalStorage = (key, initialValue) => {
    const [value, setValue] = useState(() => {
        const storedValue =
            localStorage.getItem(key);
        return storedValue ?
            JSON.parse(storedValue) :
            initialValue;
    });
 
    useEffect(() => {
        console.log("Data changed, updating localStorage...");
        localStorage
            .setItem(key, JSON.stringify(value));
 
        return () => {
            console.log("Cleanup: Removing the listener...");
        };
    }, [key, value]);
 
    return [value, setValue];
}
 
const App = () => {
    const [name, setName] = useLocalStorage('name', '');
 
    console.log("Rendering App component...");
 
    return (
        <div>
            <input
                type="text"
                value={name}
                onChange={
                    (e) =>
                        setName(e.target.value)
                }
                placeholder="Enter your name" />
            <p>
                Hello,
                {
                    name ?
                        name :
                        'Provide the Input here'
                }
            </p>
        </div>
    );
}
 
export default App;


Output:

gfg60

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads