Open In App

How to handle side effects in a Custom Hook?

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:

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




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:

Output


Article Tags :