Study 10 practical React Hooks

📢 purpose

This project is a project to study React by taking the lecture of “10 Real React Hooks” by Nomad Coder.

The code was produced using https://codesandbox.io/ .

📢 Study content

📑 Hook

What is a Hook?

A function that allows you to link React state and Lifecycle functions in a function component (introduced from version 16.8)

Rules for using hooks

  • Hook call is possible only at the top level
  • It can be called only within the React function component, and should not be called inside a general JavaScript function (can be called in a custom hook)

Why Hook was created

  • Difficulty in reusing state logic between components
  • Complex components are difficult to understand
  • Class component confuses both humans and machines

Reference site

Hook introduction

📑 useState

What is useState?

It plays the same role as this.state used in the existing class component.

It returns two pairs: a state variable and a function that updates the state.

const [age, setAge] = useState(20);

This expression is called structure decomposition assignment.

  • function
function App() {
  const [item, setItem] = useState(1);
  const incrementItem = () => setItem(item + 1);
  const decrementItem = () => setItem(item - 1);
  return (
    <div className="App">
      <h1>Hello {item}</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={incrementItem}>Increment</button>
      <button onClick={decrementItem}>Decrement</button>
    </div>
  );
}
  • class
class App extends React.Component {
  state = {
    item: 1
  };

  render() {
    const { item } = this.state;
    return (
      <div className="App">
        <h1>Hello {item}</h1>
        <h2>Start editing to see some magic happen!</h2>
        <button onClick={this.incrementItem}>Increment</button>
        <button onClick={this.decrementItem}>Decrement</button>
      </div>
    );
  }

  incrementItem = () => {
    this.setState((state) => {
      return {
        item: state.item + 1
      };
    });
  };

  decrementItem = () => {
    this.setState((state) => {
      return {
        item: state.item + 1
      };
    });
  };
}

Reference site

useState guide

📢 Custom Hooks

📑 useInput

What is useInput?

Controlling the input role

const useInput = (initialValue, validator) => {
    const [value, setValue] = useState(initialValue);
    const onChange = (event) => {
        const {
            target: { value }
        } = event;
        let willUpdate = true;
        if (typeof validator === "function") {
            willUpdate = validator(value);
        }
        if (willUpdate) {
            setValue(value);
        }
    };
    return { value, onChange };
};

function App() {
	const maxLen = (value) => value.length < 10;
	const name = useInput("your name", maxLen);
	return (
	<div className="App">
		<h1>Hello</h1>
      	<input placeholder="Name" {...name} />
    </div>
  );
}

📑 useTabs

What is useTabs?

Making it very easy to use tabs for menus or anything on your website

const useTabs = (initialTab, allTabs) => {
    if (!allTabs || !Array.isArray(allTabs)) {
        return;
    }
    const [currentIndex, setCurrentIndex] = useState(initialTab);
    return {
        currnetItem: allTabs[currentIndex],
        changeItem: setCurrentIndex
    };
};

const content = [
    {
        tab: "Section 1",
        content: "I'm the content of the Section 1"
    },
    {
        tab: "Section 2",
        content: "I'm the content of the Section 2"
    }
];

function App() {
    const { currnetItem, changeItem } = useTabs(0, content);
    return (
        <div className="App">
            <h1>Hello</h1>
            {content.map((section, index) => (
                <button key={index} onClick={() => changeItem(index)}>
                    {section.tab}
                </button>
            ))}
            <div>{currnetItem.content}</div>
        </div>
    );
}

📑 useTitle

What is useTitle?

Changing the title of react document with several hoots

const useTitle = (initialTitle) => {
    const [title, setTitle] = useState(initialTitle);
    const updateTitle = () => {
        const htmlTitle = document.querySelector("title");
        htmlTitle.innerText = title;
    };
    useEffect(updateTitle, [title]);
    return setTitle;
};

function App() {
    const titleUpdater = useTitle("Loading...");
    setTimeout(() => titleUpdater("home"), 5000);
    return (
        <div className="App">
            <h1>Hello</h1>
        </div>
    );
}

📑 useClick

What is useClick?

Event cycles when the user clicks the element

const useClick = (onClick) => {
    if (typeof onclick !== "function") {
        return;
    }
    const element = useRef();
    useEffect(() => {
        if (element.current) {
            element.current.addEventListener("click", onClick);
        }
        return () => {
            if (element.current) {
                element.current.removeEventListener("click", onClick);
            }
        };
    }, []);
    return element;
};

function App() {
    const onClick = () => console.log("hello");
    const title = useClick(onClick);
    return (
        <div className="App">
            <h1 ref={title}>Hello</h1>
        </div>
    );
}

📑 useHover

What is useHover?

Event cycle at the point when the user hovered the element

const useHover = (onHover) => {
    if (typeof onHover !== "function") {
        return;
    }
    const element = useRef();
    useEffect(() => {
        if (element.current) {
            element.current.addEventListener("mouseenter", onHover);
        }
        return () => {
            if (element.current) {
                element.current.removeEventListener("mouseenter", onHover);
            }
        };
    }, []);
    return element;
};

function App() {
    const onHover = () => console.log("hello");
    const title = useHover(onHover);
    return (
        <div className="App">
            <h1 ref={title}>Hello</h1>
        </div>
    );
}

📑 useConfirm

What is useConfirm?

Checking whether a user fires any event

const useConfirm = (message = "", onConfirm, onCancel) => {
    if (!onConfirm || typeof onConfirm !== "function") {
        return;
    }
    if (onCancel && typeof onCancel !== "function") {
        return;
    }
    const confirmAction = () => {
        if (confirm( message ) )  { 
            onConfirm ( ) ; 
        }  else  { 
            onCancel ( ) ; 
        } 
    } ; 
    return  confirmAction ; 
} ;

function App() {
    const deleteWorld = () => console.log("Deleting the world...");
    const abort = () => console.log("Aborted");
    const confirmDelete = useConfirm("Are you sure", deleteWorld, abort);
    return (
        <div className="App">
            <h1>Hello</h1>
            <button onClick={confirmDelete}>Delete the world</button>
        </div>
    );
}

📑 usePreventLeave

What is usePreventLeave?

Checking when the user wants to leave the page without saving any changes or anything

const usePreventLeave = () => {
    const listener = (event) => {
        event.preventDefault();
        event.returnValue = "";
    };
    const enablePrevent = () => window.addEventListener("beforeunload", listener);
    const disaPrevent = () =>
        window.removeEventListener("beforeunload", listener);
    return { enablePrevent, disaPrevent };
};

function App() {
    const { enablePrevent, disaPrevent } = usePreventLeave();
    return (
        <div className="App">
            <h1>Hello</h1>
            <button onClick={enablePrevent}>Protect</button>
            <button onClick={disaPrevent}>Unprotect</button>
        </div>
    );
}

📑 useBeforeLeave

What is useBeforeLeave?

Detect when the user leaves the page and execute the function

const useBeforeLeave = (onBefore) => {
    if (typeof onBefore !== "function") {
        return;
    }
    const handle = (event) => {
        const { clientY } = event;
        if (clientY <= 0) {
            onBefore();
        }
    };
    useEffect(() => {
        document.addEventListener("mouseleave", handle);
        return () => document.removeEventListener("mouseleave", handle);
    }, []);
};

function App() {
    const begForLife = () => console.log("Pls dont leave");
    useBeforeLeave(begForLife);
    return (
        <div className="App">
            <h1>Hello</h1>
        </div>
    );
}

📑 useFadeIn

What is useFadeIn?

Making the animation slowly disappear into the element no matter what element

const useFadeIn = (duration = 1, delay = 0) => {
    if (typeof duration !== "number" || typeof delay !== "number") {
        return;
    }
    const element = useRef();
    useEffect(() => {
        if (element.current) {
            const { current } = element;
            current.style.transition = `opacity ${duration}s ease-in-out ${delay}s`;
            current.style.opacity = 1;
        }
    }, []);
    return { ref: element, style: { opacity: 0 } };
};

function App() {
    const fadeInH1 = useFadeIn(1, 2);
    const fadeInP = useFadeIn(2, 3);
    return (
        <div className="App">
            <h1 {...fadeInH1}>Hello</h1>
            <p {...fadeInP}>
                Lorem ipsum carrots enhanced rebates. snacks
                a pleasure due denouncing the truth! Currently, the less the consequences thereof,
                that nothing in this man of sorrows in the explication thereof, consectetur of them deal corruptly fall of mind, so that,
                the right to take pleasure in with your pleasures.
        </p>
        </div>
    );
}

📑 useNetwork

What is useNetwork?

Detecting whether you are currently online or offline

const useNetwork = (onChange) => {
    const [status, setStatus] = useState(navigator.onLine);
    const handleChange = (event) => {
        if (typeof onChange === "function") {
            onChange(navigator.onLine);
        }
        setStatus(navigator.onLine);
    };
    useEffect(() => {
        window.addEventListener("online", handleChange);
        window.addEventListener("offline", handleChange);
        return () => {
            window.removeEventListener("online", handleChange);
            window.removeEventListener("offline", handleChange);
        };
    }, []);
    return status;
};

function App() {
    const handleNetworkChange = (online) => {
        console.log(online ? "We just went online" : "We are offline");
    };
    const onLine = useNetwork(handleNetworkChange);
    return (
        <div className="App">
            <h1>Hello</h1>
            <h1>{onLine ? "Online" : "Offline"}</h1>
        </div>
    );
}

📑 useScroll

What is useScroll?

Detecting and notifying when to use scrolling

const useScroll = () => {
    const [status, setStatus] = useState({ x: 0, y: 0 });
    const onScroll = () => {
        setStatus({ x: window.scrollX, y: window.scrollY });
    };
    useEffect(() => {
        window.addEventListener("scroll", onScroll);
        return () => window.removeEventListener("scroll", onScroll);
    }, []);
    return status;
};

function App() {
    const { y } = useScroll();
    return (
        <div className="App" style={{ height: "1000vh" }}>
            <h1 style={{ position: "fixed", color: y > 1000 ? "blue" : "red" }}>
                Hello
        </h1>
        </div>
    );
}

📑 useFullscreen

What is useFullscreen?

Making any element full-screen or returning to the normal screen

const useFullscreen = (callback) => {
    const element = useRef();
    const runCb = (isFull) => {
        if (callback && typeof callback === "function") {
            callback(isFull);
        }
    };
    const triggerFull = () => {
        if (element.current) {
            if (element.current.requestFullscreen) {
                element.current.requestFullscreen();
            } else if (element.current.mozRequestFullscreen) {
                element.current.mozRequestFullscreen();
            } else if (element.current.webkitRequestFullscreen) {
                element.current.webkitRequestFullscreen();
            } else if (element.current.msRequestFullscreen) {
                element.current.msRequestFullscreen();
            }
            runCb(true);
        }
    };
    const exitFull = () => {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        runCb(false);
    };
    return { element, triggerFull, exitFull };
};

function App() {
    const onFullS = (isFull) => {
        console.log(isFull ? "We are full" : "We are small");
    };
    const { element, triggerFull, exitFull } = useFullscreen(onFullS);
    return (
        <div className="App">
            <h1>Hello</h1>
            <div ref={element}>
                <img
                    src="https://mblogthumb-phinf.pstatic.net/MjAxODAyMDZfMTk0/MDAxNTE3OTA5NDQ3MjYy._A5goNQD2IUU1ZVepodSGGYRkzsj6Qzvo-7N40S-OzMg.ITZqPfqEABCTd4tuLxQrMXY-nRU40sD2tMpDZRkA_34g.JPEG.xbeebee/%EC%9B%B0%EC%8B%9C%EC%BD%94%EA%B8%B0.jpg?type=w800"
                    alt="img"
                />
                <button onClick={exitFull}>Exit Fullscreen</button>
            </div>
            <button onClick={triggerFull}>Make Fullscreen</button>
        </div>
    );
}

📑 useNotification

What is useNotification?

Sending an alarm to the user when using the notification API

const useNotification = (title, options) => {
    if (!("Notification" in window)) {
        return;
    }
    const fireNotif = () => {
        if (Notification.permission !== "granted") {
            Notification.requestPermission().then((permission) => {
                if (permission === "granted") {
                    new Notification(title, options);
                } else {
                    return;
                }
            });
        } else {
            new Notification(title, options);
        }
    };
    return fireNotif;
};

function App() {
    const triggerNotif = useNotification("Can I steal your kimchi?", {
        body: "I love kimchi dont you"
    });
    return (
        <div className="App">
            <h1>Hello</h1>
            <button onClick={triggerNotif}>Hello</button>
        </div>
    );
}

Notification API

📑 useAxios

What is useAxios?

Something like a wrapper for HTTP requests client axios

const useAxios = (options, axiosInstance = defaultAxios) => {
    const [state, setSate] = useState({
        loading: true,
        error: null,
        data: null
    });
    const [trigger, setTrigger] = useState(0);
    if (!options.url) {
        return;
    }
    const refetch = () => {
        setSate({
            ...state,
            loading: true
        });
        setTrigger(Date.now());
    };
    useEffect(() => {
        axiosInstance(options)
            .then((data) => {
                setSate({
                    ...state,
                    loading: false,
                    data
                });
            })
            .catch((error) => {
                setSate({
                    ...state,
                    loading: false,
                    error
                });
            });
    }, [trigger]);
    return { ...state, refetch };
};

function App() {
    const { loading, data, refetch } = useAxios({
        url:
            "https://cors-anywhere.herokuapp.com/https://yts.am/api/v2/list_movies.json"
    });
    console.log(loading, data, JSON.stringify(data), refetch);
    return (
        <div className="App">
            <h1>{data && data.status}</h1>
            <h1>{loading && "Loading"}</h1>
            <button onClick={refetch}>Refetch</button>
        </div>
    );
}

📢 Study progress

  • useState
  • useInput
  • useTabs
  • useTitle
  • useClick
  • useHover
  • useConfirm - hook 사용 x
  • usePreventLeave - hook 사용 x
  • useBeforeLeave
  • useFadeIn
  • useNetwork
  • useScroll
  • useFullscreen
  • useNotification
  • useAxios

Download Details:

Author: leeseungho02

Source Code: https://github.com/leeseungho02/practicet-type-react-hooks

#react #reactjs #javascript

Study 10 practical React Hooks
55.55 GEEK