Skip to content

Commit

Permalink
replace useRef with useCallback
Browse files Browse the repository at this point in the history
  • Loading branch information
siriwatknp committed Aug 18, 2021
1 parent fa5bfe0 commit 9064d77
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions docs/src/components/home/ElementPointer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,15 @@ import Box, { BoxProps } from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import { debounce } from '@material-ui/core/utils';

const PointerContext = React.createContext<undefined | React.Dispatch<React.SetStateAction<Data>>>(
undefined,
);
const PointerContext = React.createContext<undefined | ((data: Data) => void)>(undefined);

export const withPointer = <T extends React.ElementType>(
Component: T,
options: { id: string; name: string },
) => {
const WithPointer = (props: unknown) => {
const root = React.useRef<null | HTMLElement>(null);
const setData = React.useContext(PointerContext);
const handleMouseOver = React.useContext(PointerContext);
return (
<React.Fragment>
{/* @ts-ignore */}
Expand All @@ -22,8 +20,8 @@ export const withPointer = <T extends React.ElementType>(
{...props}
onMouseOver={(event: React.MouseEvent) => {
event.stopPropagation();
if (setData && root.current) {
setData({
if (handleMouseOver && root.current) {
handleMouseOver({
id: options.id,
target: root.current,
name: options.name,
Expand All @@ -50,16 +48,22 @@ export default function PointerContainer({
name: null,
target: null,
});
const debouncedSetData = React.useRef(debounce(setData, 200));
/* eslint-disable react-hooks/exhaustive-deps */
const handleMouseOver = React.useCallback(
debounce((elementData: Data) => {
setData(elementData);
}, 200),
[],
);
React.useEffect(() => {
if (onElementChange) onElementChange(data);
}, [data, onElementChange]);
return (
<PointerContext.Provider value={debouncedSetData.current}>
<PointerContext.Provider value={handleMouseOver}>
<Box
ref={container}
{...props}
onMouseLeave={() => debouncedSetData.current({ id: null, name: null, target: null })}
onMouseLeave={() => handleMouseOver({ id: null, name: null, target: null })}
sx={{ position: 'relative', ...props.sx }}
>
{props.children}
Expand Down

0 comments on commit 9064d77

Please sign in to comment.