mirror of
https://github.com/langgenius/dify.git
synced 2026-04-27 11:06:46 +08:00
[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:
parent
cd47a47c3b
commit
df43c6ab8a
@ -38,7 +38,7 @@ const Annotation: FC<Props> = (props) => {
|
|||||||
const [isShowEdit, setIsShowEdit] = useState(false)
|
const [isShowEdit, setIsShowEdit] = useState(false)
|
||||||
const [annotationConfig, setAnnotationConfig] = useState<AnnotationReplyConfig | null>(null)
|
const [annotationConfig, setAnnotationConfig] = useState<AnnotationReplyConfig | null>(null)
|
||||||
const [isChatApp] = useState(appDetail.mode !== 'completion')
|
const [isChatApp] = useState(appDetail.mode !== 'completion')
|
||||||
const [controlRefreshSwitch, setControlRefreshSwitch] = useState(Date.now())
|
const [controlRefreshSwitch, setControlRefreshSwitch] = useState(() => Date.now())
|
||||||
const { plan, enableBilling } = useProviderContext()
|
const { plan, enableBilling } = useProviderContext()
|
||||||
const isAnnotationFull = enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse
|
const isAnnotationFull = enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse
|
||||||
const [isShowAnnotationFullModal, setIsShowAnnotationFullModal] = useState(false)
|
const [isShowAnnotationFullModal, setIsShowAnnotationFullModal] = useState(false)
|
||||||
@ -48,7 +48,7 @@ const Annotation: FC<Props> = (props) => {
|
|||||||
const [list, setList] = useState<AnnotationItem[]>([])
|
const [list, setList] = useState<AnnotationItem[]>([])
|
||||||
const [total, setTotal] = useState(0)
|
const [total, setTotal] = useState(0)
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
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 [currItem, setCurrItem] = useState<AnnotationItem | null>(null)
|
||||||
const [isShowViewModal, setIsShowViewModal] = useState(false)
|
const [isShowViewModal, setIsShowViewModal] = useState(false)
|
||||||
const [selectedIds, setSelectedIds] = useState<string[]>([])
|
const [selectedIds, setSelectedIds] = useState<string[]>([])
|
||||||
|
|||||||
@ -25,7 +25,7 @@ const PromptEditorHeightResizeWrap: FC<Props> = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const [clientY, setClientY] = useState(0)
|
const [clientY, setClientY] = useState(0)
|
||||||
const [isResizing, setIsResizing] = useState(false)
|
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 [oldHeight, setOldHeight] = useState(height)
|
||||||
|
|
||||||
const handleStartResize = useCallback((e: React.MouseEvent<HTMLElement>) => {
|
const handleStartResize = useCallback((e: React.MouseEvent<HTMLElement>) => {
|
||||||
|
|||||||
@ -53,7 +53,7 @@ const ConfigModal: FC<IConfigModalProps> = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const { modelConfig } = useContext(ConfigContext)
|
const { modelConfig } = useContext(ConfigContext)
|
||||||
const { t } = useTranslation()
|
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 { type, label, variable, options, max_length } = tempPayload
|
||||||
const modalRef = useRef<HTMLDivElement>(null)
|
const modalRef = useRef<HTMLDivElement>(null)
|
||||||
const appDetail = useAppStore(state => state.appDetail)
|
const appDetail = useAppStore(state => state.appDetail)
|
||||||
|
|||||||
@ -35,8 +35,8 @@ const useAdvancedPromptConfig = ({
|
|||||||
setStop,
|
setStop,
|
||||||
}: Param) => {
|
}: Param) => {
|
||||||
const isAdvancedPrompt = promptMode === PromptMode.advanced
|
const isAdvancedPrompt = promptMode === PromptMode.advanced
|
||||||
const [chatPromptConfig, setChatPromptConfig] = useState<ChatPromptConfig>(clone(DEFAULT_CHAT_PROMPT_CONFIG))
|
const [chatPromptConfig, setChatPromptConfig] = useState<ChatPromptConfig>(() => clone(DEFAULT_CHAT_PROMPT_CONFIG))
|
||||||
const [completionPromptConfig, setCompletionPromptConfig] = useState<CompletionPromptConfig>(clone(DEFAULT_COMPLETION_PROMPT_CONFIG))
|
const [completionPromptConfig, setCompletionPromptConfig] = useState<CompletionPromptConfig>(() => clone(DEFAULT_COMPLETION_PROMPT_CONFIG))
|
||||||
|
|
||||||
const currentAdvancedPrompt = (() => {
|
const currentAdvancedPrompt = (() => {
|
||||||
if (!isAdvancedPrompt)
|
if (!isAdvancedPrompt)
|
||||||
|
|||||||
@ -55,8 +55,8 @@ const DatePicker = ({
|
|||||||
const [currentDate, setCurrentDate] = useState(inputValue || defaultValue)
|
const [currentDate, setCurrentDate] = useState(inputValue || defaultValue)
|
||||||
const [selectedDate, setSelectedDate] = useState(inputValue)
|
const [selectedDate, setSelectedDate] = useState(inputValue)
|
||||||
|
|
||||||
const [selectedMonth, setSelectedMonth] = useState((inputValue || defaultValue).month())
|
const [selectedMonth, setSelectedMonth] = useState(() => (inputValue || defaultValue).month())
|
||||||
const [selectedYear, setSelectedYear] = useState((inputValue || defaultValue).year())
|
const [selectedYear, setSelectedYear] = useState(() => (inputValue || defaultValue).year())
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleClickOutside = (event: MouseEvent) => {
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
|
|||||||
@ -28,7 +28,7 @@ const TimePicker = ({
|
|||||||
const [isOpen, setIsOpen] = useState(false)
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
const containerRef = useRef<HTMLDivElement>(null)
|
||||||
const isInitial = useRef(true)
|
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(() => {
|
useEffect(() => {
|
||||||
const handleClickOutside = (event: MouseEvent) => {
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
|
|||||||
@ -37,7 +37,7 @@ const removeEndThink = (children: any): any => {
|
|||||||
|
|
||||||
const useThinkTimer = (children: any) => {
|
const useThinkTimer = (children: any) => {
|
||||||
const { isResponding } = useChatContext()
|
const { isResponding } = useChatContext()
|
||||||
const [startTime] = useState(Date.now())
|
const [startTime] = useState(() => Date.now())
|
||||||
const [elapsedTime, setElapsedTime] = useState(0)
|
const [elapsedTime, setElapsedTime] = useState(0)
|
||||||
const [isComplete, setIsComplete] = useState(false)
|
const [isComplete, setIsComplete] = useState(false)
|
||||||
const timerRef = useRef<NodeJS.Timeout>()
|
const timerRef = useRef<NodeJS.Timeout>()
|
||||||
|
|||||||
@ -93,7 +93,7 @@ const NotionPageSelector = ({
|
|||||||
const defaultSelectedPagesId = useMemo(() => {
|
const defaultSelectedPagesId = useMemo(() => {
|
||||||
return [...Array.from(pagesMapAndSelectedPagesId[1]), ...(value || [])]
|
return [...Array.from(pagesMapAndSelectedPagesId[1]), ...(value || [])]
|
||||||
}, [pagesMapAndSelectedPagesId, value])
|
}, [pagesMapAndSelectedPagesId, value])
|
||||||
const [selectedPagesId, setSelectedPagesId] = useState<Set<string>>(new Set(defaultSelectedPagesId))
|
const [selectedPagesId, setSelectedPagesId] = useState<Set<string>>(() => new Set(defaultSelectedPagesId))
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setSelectedPagesId(new Set(defaultSelectedPagesId))
|
setSelectedPagesId(new Set(defaultSelectedPagesId))
|
||||||
|
|||||||
@ -21,7 +21,7 @@ const TabSlider: FC<TabSliderProps> = ({
|
|||||||
onChange,
|
onChange,
|
||||||
options,
|
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 [sliderStyle, setSliderStyle] = useState({})
|
||||||
const { data: pluginList } = useInstalledPluginList()
|
const { data: pluginList } = useInstalledPluginList()
|
||||||
|
|
||||||
|
|||||||
@ -38,7 +38,7 @@ const CustomWebAppBrand = () => {
|
|||||||
isCurrentWorkspaceManager,
|
isCurrentWorkspaceManager,
|
||||||
} = useAppContext()
|
} = useAppContext()
|
||||||
const [fileId, setFileId] = useState('')
|
const [fileId, setFileId] = useState('')
|
||||||
const [imgKey, setImgKey] = useState(Date.now())
|
const [imgKey, setImgKey] = useState(() => Date.now())
|
||||||
const [uploadProgress, setUploadProgress] = useState(0)
|
const [uploadProgress, setUploadProgress] = useState(0)
|
||||||
const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
|
const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
|
||||||
const isSandbox = enableBilling && plan.type === Plan.sandbox
|
const isSandbox = enableBilling && plan.type === Plan.sandbox
|
||||||
|
|||||||
@ -6,7 +6,7 @@ import { useLanguage } from '@/app/components/header/account-setting/model-provi
|
|||||||
const MaintenanceNotice = () => {
|
const MaintenanceNotice = () => {
|
||||||
const locale = useLanguage()
|
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 = () => {
|
const handleJumpNotice = () => {
|
||||||
window.open(NOTICE_I18N.href, '_blank')
|
window.open(NOTICE_I18N.href, '_blank')
|
||||||
}
|
}
|
||||||
|
|||||||
@ -12,7 +12,7 @@ type CountdownProps = {
|
|||||||
|
|
||||||
export default function Countdown({ onResend }: CountdownProps) {
|
export default function Countdown({ onResend }: CountdownProps) {
|
||||||
const { t } = useTranslation()
|
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({
|
const [time] = useCountDown({
|
||||||
leftTime,
|
leftTime,
|
||||||
onEnd: () => {
|
onEnd: () => {
|
||||||
|
|||||||
@ -65,7 +65,7 @@ const MCPModal = ({
|
|||||||
const originalServerID = data?.server_identifier
|
const originalServerID = data?.server_identifier
|
||||||
const [url, setUrl] = React.useState(data?.server_url || '')
|
const [url, setUrl] = React.useState(data?.server_url || '')
|
||||||
const [name, setName] = React.useState(data?.name || '')
|
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 [showAppIconPicker, setShowAppIconPicker] = useState(false)
|
||||||
const [serverIdentifier, setServerIdentifier] = React.useState(data?.server_identifier || '')
|
const [serverIdentifier, setServerIdentifier] = React.useState(data?.server_identifier || '')
|
||||||
const [timeout, setMcpTimeout] = React.useState(data?.timeout || 30)
|
const [timeout, setMcpTimeout] = React.useState(data?.timeout || 30)
|
||||||
|
|||||||
@ -33,7 +33,7 @@ export const useResizePanel = (params?: UseResizePanelParams) => {
|
|||||||
const initContainerWidthRef = useRef(0)
|
const initContainerWidthRef = useRef(0)
|
||||||
const initContainerHeightRef = useRef(0)
|
const initContainerHeightRef = useRef(0)
|
||||||
const isResizingRef = useRef(false)
|
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) => {
|
const handleStartResize = useCallback((e: MouseEvent) => {
|
||||||
initXRef.current = e.clientX
|
initXRef.current = e.clientX
|
||||||
|
|||||||
@ -16,7 +16,7 @@ const strToKeyValueList = (value: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const useKeyValueList = (value: string, onChange: (value: string) => void, noFilter?: boolean) => {
|
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[]) => {
|
const setList = (l: KeyValue[]) => {
|
||||||
doSetList(l.map((item) => {
|
doSetList(l.map((item) => {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@ -55,7 +55,7 @@ const JsonSchemaConfig: FC<JsonSchemaConfigProps> = ({
|
|||||||
const docLink = useDocLink()
|
const docLink = useDocLink()
|
||||||
const [currentTab, setCurrentTab] = useState(SchemaView.VisualEditor)
|
const [currentTab, setCurrentTab] = useState(SchemaView.VisualEditor)
|
||||||
const [jsonSchema, setJsonSchema] = useState(defaultSchema || DEFAULT_SCHEMA)
|
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 [btnWidth, setBtnWidth] = useState(0)
|
||||||
const [parseError, setParseError] = useState<Error | null>(null)
|
const [parseError, setParseError] = useState<Error | null>(null)
|
||||||
const [validationError, setValidationError] = useState<string>('')
|
const [validationError, setValidationError] = useState<string>('')
|
||||||
|
|||||||
@ -34,7 +34,7 @@ const ClassItem: FC<Props> = ({
|
|||||||
filterVar,
|
filterVar,
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const [instanceId, setInstanceId] = useState(uniqueId())
|
const [instanceId, setInstanceId] = useState(() => uniqueId())
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setInstanceId(`${nodeId}-${uniqueId()}`)
|
setInstanceId(`${nodeId}-${uniqueId()}`)
|
||||||
|
|||||||
@ -69,7 +69,7 @@ const ValueContent = ({
|
|||||||
const [json, setJson] = useState('')
|
const [json, setJson] = useState('')
|
||||||
const [parseError, setParseError] = useState<Error | null>(null)
|
const [parseError, setParseError] = useState<Error | null>(null)
|
||||||
const [validationError, setValidationError] = useState<string>('')
|
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 })
|
const { run: debounceValueChange } = useDebounceFn(handleValueChange, { wait: 500 })
|
||||||
|
|
||||||
|
|||||||
@ -68,8 +68,8 @@ const WorkflowPreview = ({
|
|||||||
viewport,
|
viewport,
|
||||||
className,
|
className,
|
||||||
}: WorkflowPreviewProps) => {
|
}: WorkflowPreviewProps) => {
|
||||||
const [nodesData, setNodesData] = useState(initialNodes(nodes, edges))
|
const [nodesData, setNodesData] = useState(() => initialNodes(nodes, edges))
|
||||||
const [edgesData, setEdgesData] = useState(initialEdges(edges, nodes))
|
const [edgesData, setEdgesData] = useState(() => initialEdges(edges, nodes))
|
||||||
|
|
||||||
const onNodesChange = useCallback(
|
const onNodesChange = useCallback(
|
||||||
(changes: NodeChange[]) => setNodesData(nds => applyNodeChanges(changes, nds)),
|
(changes: NodeChange[]) => setNodesData(nds => applyNodeChanges(changes, nds)),
|
||||||
|
|||||||
@ -30,7 +30,7 @@ export default function InviteSettingsPage() {
|
|||||||
const { setLocaleOnClient } = useContext(I18n)
|
const { setLocaleOnClient } = useContext(I18n)
|
||||||
const [name, setName] = useState('')
|
const [name, setName] = useState('')
|
||||||
const [language, setLanguage] = useState(LanguagesSupported[0])
|
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 = {
|
const checkParams = {
|
||||||
url: '/activate/check',
|
url: '/activate/check',
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user