Skip to content

Commit 9422c0c

Browse files
committed
refactor: use useCallback and useMemo
1 parent 866620b commit 9422c0c

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

src/SwitchSelector.tsx

+23-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, {FC, useState, useEffect} from "react";
1+
import React, {FC, useState, useEffect, useCallback, useMemo} from "react";
22
import {
33
SwitchSelectorWrapper,
44
OptionItem,
@@ -42,14 +42,17 @@ const SwitchSelector: FC<SwitchSelectorProps> = (props) => {
4242
}
4343
}, [forcedSelectedIndex, options, selectedIndex]);
4444

45-
const handleOnClick = (index: number): void => {
46-
if (!disabled && index !== selectedIndex) {
47-
setSelectedIndex(index);
48-
onChange(options[index].value);
49-
}
50-
};
45+
const handleOnClick = useCallback(
46+
(index: number): void => {
47+
if (!disabled && index !== selectedIndex) {
48+
setSelectedIndex(index);
49+
onChange(options[index].value);
50+
}
51+
},
52+
[disabled, onChange, options, selectedIndex]
53+
);
5154

52-
const renderOptions = (): React.ReactElement[] => {
55+
const renderedOptions = useMemo(() => {
5356
return options.map((option, index) => {
5457
const isSelected = selectedIndex === index;
5558
const optionId = `${name ?? "rss"}-option-${index}`;
@@ -93,7 +96,17 @@ const SwitchSelector: FC<SwitchSelectorProps> = (props) => {
9396
</OptionItem>
9497
);
9598
});
96-
};
99+
}, [
100+
disabled,
101+
fontColor,
102+
fontSize,
103+
handleOnClick,
104+
name,
105+
optionBorderRadius,
106+
options,
107+
selectedFontColor,
108+
selectedIndex
109+
]);
97110

98111
if (!options.length) return null;
99112
return (
@@ -115,7 +128,7 @@ const SwitchSelector: FC<SwitchSelectorProps> = (props) => {
115128
role={"radiogroup"}
116129
aria-labelledby={name}
117130
>
118-
{renderOptions()}
131+
{renderedOptions}
119132
</SwitchSelectorWrapper>
120133
);
121134
};

0 commit comments

Comments
 (0)