Skip to content

Instantly share code, notes, and snippets.

@drublic
Last active September 21, 2019 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drublic/cbb99a906f8fd349298ce32b2c3b6bc8 to your computer and use it in GitHub Desktop.
Save drublic/cbb99a906f8fd349298ce32b2c3b6bc8 to your computer and use it in GitHub Desktop.
Conceptual Hooks
// Presentational Component
// contains only the UI and has a clear UI (props) for testing
import React from "react";
import Loader from "../Loader";
const Button = ({ onFocus, onBlur, hasLoader, label }) => (
<button type="button" onFocus={onFocus} onBlur={onBlur}>
{hasLoader ? <Loader /> : label}
</button>
);
export default Button;
// Higher-Order Component
// contains the state and life-cycle behavior of the component
import React, { FunctionComponent, useState, useCallback } from "react";
import Button from "./Button";
import useHasLoader from "./hooks/useHasLoader";
interface Props {
isLoading: boolean;
}
const withButton = (
Component: FunctionComponent<any>
): FunctionComponent<Props> => ({ isLoading, ...props }) => {
const [hasFocus, setHasFocus] = useState<boolean>(false);
const [hasLoader, setHasLoader] = useState<boolean>(false);
const handleFocus = useCallback(() => {
setHasFocus(true);
}, []);
const handleBlur = useCallback(() => {
setHasFocus(false);
}, []);
useHasLoader({
isLoading,
hasFocus,
setHasLoader
});
return (
<Component
hasLoader={hasLoader}
onFocus={handleFocus}
onBlur={handleBlur}
{...props}
/>
);
};
export default withButton(Button);
// Custom Hook for logic
import { useEffect } from "react";
const useHasLoader = ({ isLoading, hasFocus, setHasLoader }) => {
useEffect(() => {
if (isLoading && !hasFocus) {
return setHasLoader(true);
}
return setHasLoader(false);
}, [isLoading, hasFocus, setHasLoader]);
};
export default useHasLoader;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment