[Chore/Refactor] Implement lazy initialization for useState calls to prevent re-computation (#26252)

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asukaminato0721 <30024051+asukaminato0721@users.noreply.github.com>
This commit is contained in:
Copilot 2025-09-29 20:35:55 +09:00 committed by GitHub
parent cd47a47c3b
commit df43c6ab8a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 24 additions and 24 deletions

View File

@ -38,7 +38,7 @@ const Annotation: FC<Props> = (props) => {
const [isShowEdit, setIsShowEdit] = useState(false)
const [annotationConfig, setAnnotationConfig] = useState<AnnotationReplyConfig | null>(null)
const [isChatApp] = useState(appDetail.mode !== 'completion')
const [controlRefreshSwitch, setControlRefreshSwitch] = useState(Date.now())
const [controlRefreshSwitch, setControlRefreshSwitch] = useState(() => Date.now())
const { plan, enableBilling } = useProviderContext()
const isAnnotationFull = enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse
const [isShowAnnotationFullModal, setIsShowAnnotationFullModal] = useState(false)
@ -48,7 +48,7 @@ const Annotation: FC<Props> = (props) => {
const [list, setList] = useState<AnnotationItem[]>([])
const [total, setTotal] = useState(0)
const [isLoading, setIsLoading] = useState(false)
const [controlUpdateList, setControlUpdateList] = useState(Date.now())
const [controlUpdateList, setControlUpdateList] = useState(() => Date.now())
const [currItem, setCurrItem] = useState<AnnotationItem | null>(null)
const [isShowViewModal, setIsShowViewModal] = useState(false)
const [selectedIds, setSelectedIds] = useState<string[]>([])

View File

@ -25,7 +25,7 @@ const PromptEditorHeightResizeWrap: FC<Props> = ({
}) => {
const [clientY, setClientY] = useState(0)
const [isResizing, setIsResizing] = useState(false)
const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(getComputedStyle(document.body).userSelect)
const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(() => getComputedStyle(document.body).userSelect)
const [oldHeight, setOldHeight] = useState(height)
const handleStartResize = useCallback((e: React.MouseEvent<HTMLElement>) => {

View File

@ -53,7 +53,7 @@ const ConfigModal: FC<IConfigModalProps> = ({
}) => {
const { modelConfig } = useContext(ConfigContext)
const { t } = useTranslation()
const [tempPayload, setTempPayload] = useState<InputVar>(payload || getNewVarInWorkflow('') as any)
const [tempPayload, setTempPayload] = useState<InputVar>(() => payload || getNewVarInWorkflow('') as any)
const { type, label, variable, options, max_length } = tempPayload
const modalRef = useRef<HTMLDivElement>(null)
const appDetail = useAppStore(state => state.appDetail)

View File

@ -35,8 +35,8 @@ const useAdvancedPromptConfig = ({
setStop,
}: Param) => {
const isAdvancedPrompt = promptMode === PromptMode.advanced
const [chatPromptConfig, setChatPromptConfig] = useState<ChatPromptConfig>(clone(DEFAULT_CHAT_PROMPT_CONFIG))
const [completionPromptConfig, setCompletionPromptConfig] = useState<CompletionPromptConfig>(clone(DEFAULT_COMPLETION_PROMPT_CONFIG))
const [chatPromptConfig, setChatPromptConfig] = useState<ChatPromptConfig>(() => clone(DEFAULT_CHAT_PROMPT_CONFIG))
const [completionPromptConfig, setCompletionPromptConfig] = useState<CompletionPromptConfig>(() => clone(DEFAULT_COMPLETION_PROMPT_CONFIG))
const currentAdvancedPrompt = (() => {
if (!isAdvancedPrompt)

View File

@ -55,8 +55,8 @@ const DatePicker = ({
const [currentDate, setCurrentDate] = useState(inputValue || defaultValue)
const [selectedDate, setSelectedDate] = useState(inputValue)
const [selectedMonth, setSelectedMonth] = useState((inputValue || defaultValue).month())
const [selectedYear, setSelectedYear] = useState((inputValue || defaultValue).year())
const [selectedMonth, setSelectedMonth] = useState(() => (inputValue || defaultValue).month())
const [selectedYear, setSelectedYear] = useState(() => (inputValue || defaultValue).year())
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {

View File

@ -28,7 +28,7 @@ const TimePicker = ({
const [isOpen, setIsOpen] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const isInitial = useRef(true)
const [selectedTime, setSelectedTime] = useState(value ? getDateWithTimezone({ timezone, date: value }) : undefined)
const [selectedTime, setSelectedTime] = useState(() => value ? getDateWithTimezone({ timezone, date: value }) : undefined)
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {

View File

@ -37,7 +37,7 @@ const removeEndThink = (children: any): any => {
const useThinkTimer = (children: any) => {
const { isResponding } = useChatContext()
const [startTime] = useState(Date.now())
const [startTime] = useState(() => Date.now())
const [elapsedTime, setElapsedTime] = useState(0)
const [isComplete, setIsComplete] = useState(false)
const timerRef = useRef<NodeJS.Timeout>()

View File

@ -93,7 +93,7 @@ const NotionPageSelector = ({
const defaultSelectedPagesId = useMemo(() => {
return [...Array.from(pagesMapAndSelectedPagesId[1]), ...(value || [])]
}, [pagesMapAndSelectedPagesId, value])
const [selectedPagesId, setSelectedPagesId] = useState<Set<string>>(new Set(defaultSelectedPagesId))
const [selectedPagesId, setSelectedPagesId] = useState<Set<string>>(() => new Set(defaultSelectedPagesId))
useEffect(() => {
setSelectedPagesId(new Set(defaultSelectedPagesId))

View File

@ -21,7 +21,7 @@ const TabSlider: FC<TabSliderProps> = ({
onChange,
options,
}) => {
const [activeIndex, setActiveIndex] = useState(options.findIndex(option => option.value === value))
const [activeIndex, setActiveIndex] = useState(() => options.findIndex(option => option.value === value))
const [sliderStyle, setSliderStyle] = useState({})
const { data: pluginList } = useInstalledPluginList()

View File

@ -38,7 +38,7 @@ const CustomWebAppBrand = () => {
isCurrentWorkspaceManager,
} = useAppContext()
const [fileId, setFileId] = useState('')
const [imgKey, setImgKey] = useState(Date.now())
const [imgKey, setImgKey] = useState(() => Date.now())
const [uploadProgress, setUploadProgress] = useState(0)
const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
const isSandbox = enableBilling && plan.type === Plan.sandbox

View File

@ -6,7 +6,7 @@ import { useLanguage } from '@/app/components/header/account-setting/model-provi
const MaintenanceNotice = () => {
const locale = useLanguage()
const [showNotice, setShowNotice] = useState(localStorage.getItem('hide-maintenance-notice') !== '1')
const [showNotice, setShowNotice] = useState(() => localStorage.getItem('hide-maintenance-notice') !== '1')
const handleJumpNotice = () => {
window.open(NOTICE_I18N.href, '_blank')
}

View File

@ -12,7 +12,7 @@ type CountdownProps = {
export default function Countdown({ onResend }: CountdownProps) {
const { t } = useTranslation()
const [leftTime, setLeftTime] = useState(Number(localStorage.getItem(COUNT_DOWN_KEY) || COUNT_DOWN_TIME_MS))
const [leftTime, setLeftTime] = useState(() => Number(localStorage.getItem(COUNT_DOWN_KEY) || COUNT_DOWN_TIME_MS))
const [time] = useCountDown({
leftTime,
onEnd: () => {

View File

@ -65,7 +65,7 @@ const MCPModal = ({
const originalServerID = data?.server_identifier
const [url, setUrl] = React.useState(data?.server_url || '')
const [name, setName] = React.useState(data?.name || '')
const [appIcon, setAppIcon] = useState<AppIconSelection>(getIcon(data))
const [appIcon, setAppIcon] = useState<AppIconSelection>(() => getIcon(data))
const [showAppIconPicker, setShowAppIconPicker] = useState(false)
const [serverIdentifier, setServerIdentifier] = React.useState(data?.server_identifier || '')
const [timeout, setMcpTimeout] = React.useState(data?.timeout || 30)

View File

@ -33,7 +33,7 @@ export const useResizePanel = (params?: UseResizePanelParams) => {
const initContainerWidthRef = useRef(0)
const initContainerHeightRef = useRef(0)
const isResizingRef = useRef(false)
const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(getComputedStyle(document.body).userSelect)
const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(() => getComputedStyle(document.body).userSelect)
const handleStartResize = useCallback((e: MouseEvent) => {
initXRef.current = e.clientX

View File

@ -16,7 +16,7 @@ const strToKeyValueList = (value: string) => {
}
const useKeyValueList = (value: string, onChange: (value: string) => void, noFilter?: boolean) => {
const [list, doSetList] = useState<KeyValue[]>(value ? strToKeyValueList(value) : [])
const [list, doSetList] = useState<KeyValue[]>(() => value ? strToKeyValueList(value) : [])
const setList = (l: KeyValue[]) => {
doSetList(l.map((item) => {
return {

View File

@ -55,7 +55,7 @@ const JsonSchemaConfig: FC<JsonSchemaConfigProps> = ({
const docLink = useDocLink()
const [currentTab, setCurrentTab] = useState(SchemaView.VisualEditor)
const [jsonSchema, setJsonSchema] = useState(defaultSchema || DEFAULT_SCHEMA)
const [json, setJson] = useState(JSON.stringify(jsonSchema, null, 2))
const [json, setJson] = useState(() => JSON.stringify(jsonSchema, null, 2))
const [btnWidth, setBtnWidth] = useState(0)
const [parseError, setParseError] = useState<Error | null>(null)
const [validationError, setValidationError] = useState<string>('')

View File

@ -34,7 +34,7 @@ const ClassItem: FC<Props> = ({
filterVar,
}) => {
const { t } = useTranslation()
const [instanceId, setInstanceId] = useState(uniqueId())
const [instanceId, setInstanceId] = useState(() => uniqueId())
useEffect(() => {
setInstanceId(`${nodeId}-${uniqueId()}`)

View File

@ -69,7 +69,7 @@ const ValueContent = ({
const [json, setJson] = useState('')
const [parseError, setParseError] = useState<Error | null>(null)
const [validationError, setValidationError] = useState<string>('')
const [fileValue, setFileValue] = useState<any>(formatFileValue(currentVar))
const [fileValue, setFileValue] = useState<any>(() => formatFileValue(currentVar))
const { run: debounceValueChange } = useDebounceFn(handleValueChange, { wait: 500 })

View File

@ -68,8 +68,8 @@ const WorkflowPreview = ({
viewport,
className,
}: WorkflowPreviewProps) => {
const [nodesData, setNodesData] = useState(initialNodes(nodes, edges))
const [edgesData, setEdgesData] = useState(initialEdges(edges, nodes))
const [nodesData, setNodesData] = useState(() => initialNodes(nodes, edges))
const [edgesData, setEdgesData] = useState(() => initialEdges(edges, nodes))
const onNodesChange = useCallback(
(changes: NodeChange[]) => setNodesData(nds => applyNodeChanges(changes, nds)),

View File

@ -30,7 +30,7 @@ export default function InviteSettingsPage() {
const { setLocaleOnClient } = useContext(I18n)
const [name, setName] = useState('')
const [language, setLanguage] = useState(LanguagesSupported[0])
const [timezone, setTimezone] = useState(Intl.DateTimeFormat().resolvedOptions().timeZone || 'America/Los_Angeles')
const [timezone, setTimezone] = useState(() => Intl.DateTimeFormat().resolvedOptions().timeZone || 'America/Los_Angeles')
const checkParams = {
url: '/activate/check',