Add memoization

This commit is contained in:
Willian Mitsuda 2021-10-22 15:50:31 -03:00
parent f459f4c20c
commit e99e5c35ea
2 changed files with 26 additions and 17 deletions

View File

@ -1,4 +1,4 @@
import React from "react"; import React, { useMemo } from "react";
import { useSelectionContext } from "../useSelection"; import { useSelectionContext } from "../useSelection";
type AddressHighlighterProps = React.PropsWithChildren<{ type AddressHighlighterProps = React.PropsWithChildren<{
@ -10,12 +10,15 @@ const AddressHighlighter: React.FC<AddressHighlighterProps> = ({
children, children,
}) => { }) => {
const [selection, setSelection] = useSelectionContext(); const [selection, setSelection] = useSelectionContext();
const select = () => { const [select, deselect] = useMemo(() => {
setSelection({ type: "address", content: address }); const _select = () => {
}; setSelection({ type: "address", content: address });
const deselect = () => { };
setSelection(null); const _deselect = () => {
}; setSelection(null);
};
return [_select, _deselect];
}, [setSelection, address]);
return ( return (
<div <div

View File

@ -1,23 +1,29 @@
import React, { useState, useContext } from "react"; import {
Dispatch,
SetStateAction,
createContext,
useState,
useContext,
} from "react";
export type Selection = { export type Selection = {
type: "address" | "value"; type: "address" | "value";
content: string; content: string;
}; };
type OptionalSelection = Selection | null;
export const useSelection = (): [ export const useSelection = (): [
Selection | null, OptionalSelection,
React.Dispatch<React.SetStateAction<Selection | null>> Dispatch<SetStateAction<OptionalSelection>>
] => { ] => {
const [selection, setSelection] = useState<Selection | null>(null); return useState<OptionalSelection>(null);
return [selection, setSelection];
}; };
export const SelectionContext = React.createContext< export const SelectionContext = createContext<ReturnType<typeof useSelection>>(
ReturnType<typeof useSelection> null!
>(null!); );
export const useSelectionContext = () => { export const useSelectionContext = () => {
const ctx = useContext(SelectionContext); return useContext(SelectionContext);
return ctx;
}; };