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

Closed
opened 2026-02-21 20:49:20 -05:00 by yindo · 0 comments
Owner

Original Pull Request: https://github.com/langgenius/dify/pull/26252

State: closed
Merged: Yes


This PR implements lazy initialization for useState calls that involve function calls in their initial values to prevent unnecessary re-computation on every render.

Problem

Previously, many useState calls were executing functions directly in their initial value parameter:

const [json, setJson] = useState(JSON.stringify(jsonSchema, null, 2))
const [startTime] = useState(Date.now())
const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(getComputedStyle(document.body).userSelect)

This pattern causes the functions to be executed on every component render, even though the initial value is only needed once during component initialization. This leads to:

  • Unnecessary performance overhead
  • Repeated DOM queries and API calls
  • Inefficient memory usage

Solution

Converted all useState calls with function calls to use lazy initialization:

const [json, setJson] = useState(() => JSON.stringify(jsonSchema, null, 2))
const [startTime] = useState(() => Date.now())
const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(() => getComputedStyle(document.body).userSelect)

Changes Made

Fixed 20+ useState patterns across 20 files, including:

  • DOM computations: getComputedStyle(document.body).userSelect
  • JSON operations: JSON.stringify(jsonSchema, null, 2)
  • Date operations: Date.now() (multiple instances)
  • Object cloning: clone(DEFAULT_CHAT_PROMPT_CONFIG)
  • Constructor calls: new Set(defaultSelectedPagesId)
  • Array methods: options.findIndex(option => option.value === value)
  • API calls: Intl.DateTimeFormat().resolvedOptions().timeZone
  • localStorage access: localStorage.getItem('hide-maintenance-notice')
  • Custom utilities: uniqueId(), strToKeyValueList(), formatFileValue()

Benefits

  • Performance: Functions execute only once during initialization instead of every render
  • Memory efficiency: Prevents unnecessary object creation and computation cycles
  • Best practices: Follows React recommendations and ESLint rule hooks-extra-prefer-use-state-lazy-initialization
  • Code consistency: Standardizes useState patterns across the codebase

All changes maintain existing functionality while improving component performance through proper lazy initialization.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • fonts.googleapis.com

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

This section details on the original issue you should resolve

<issue_title>[Chore/Refactor] using lazy initial</issue_title>
<issue_description>### Self Checks

  • I have read the Contributing Guide and Language Policy.
  • This is only for refactoring, if you would like to ask a question, please head to Discussions.
  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report, otherwise it will be closed.
  • 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • Please do not modify this template :) and fill in all the required fields.

Description

To prevent re-computation, consider using lazy initial state for useState calls that involve function calls.

Motivation

To prevent re-computation.

Additional Context

https://eslint-react.xyz/docs/rules/hooks-extra-prefer-use-state-lazy-initialization</issue_description>

Comments on the Issue (you are @copilot in this section)

Fixes langgenius/dify#25213

💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

**Original Pull Request:** https://github.com/langgenius/dify/pull/26252 **State:** closed **Merged:** Yes --- This PR implements lazy initialization for useState calls that involve function calls in their initial values to prevent unnecessary re-computation on every render. ## Problem Previously, many useState calls were executing functions directly in their initial value parameter: ```typescript const [json, setJson] = useState(JSON.stringify(jsonSchema, null, 2)) const [startTime] = useState(Date.now()) const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(getComputedStyle(document.body).userSelect) ``` This pattern causes the functions to be executed on every component render, even though the initial value is only needed once during component initialization. This leads to: - Unnecessary performance overhead - Repeated DOM queries and API calls - Inefficient memory usage ## Solution Converted all useState calls with function calls to use lazy initialization: ```typescript const [json, setJson] = useState(() => JSON.stringify(jsonSchema, null, 2)) const [startTime] = useState(() => Date.now()) const [prevUserSelectStyle, setPrevUserSelectStyle] = useState(() => getComputedStyle(document.body).userSelect) ``` ## Changes Made Fixed 20+ useState patterns across 20 files, including: - **DOM computations**: `getComputedStyle(document.body).userSelect` - **JSON operations**: `JSON.stringify(jsonSchema, null, 2)` - **Date operations**: `Date.now()` (multiple instances) - **Object cloning**: `clone(DEFAULT_CHAT_PROMPT_CONFIG)` - **Constructor calls**: `new Set(defaultSelectedPagesId)` - **Array methods**: `options.findIndex(option => option.value === value)` - **API calls**: `Intl.DateTimeFormat().resolvedOptions().timeZone` - **localStorage access**: `localStorage.getItem('hide-maintenance-notice')` - **Custom utilities**: `uniqueId()`, `strToKeyValueList()`, `formatFileValue()` ## Benefits - **Performance**: Functions execute only once during initialization instead of every render - **Memory efficiency**: Prevents unnecessary object creation and computation cycles - **Best practices**: Follows React recommendations and ESLint rule `hooks-extra-prefer-use-state-lazy-initialization` - **Code consistency**: Standardizes useState patterns across the codebase All changes maintain existing functionality while improving component performance through proper lazy initialization. > [!WARNING] > > <details> > <summary>Firewall rules blocked me from connecting to one or more addresses (expand for details)</summary> > > #### I tried to connect to the following addresses, but was blocked by firewall rules: > > - `fonts.googleapis.com` > > If you need me to access, download, or install something from one of these locations, you can either: > > - Configure [Actions setup steps](https://gh.io/copilot/actions-setup-steps) to set up my environment, which run before the firewall is enabled > - Add the appropriate URLs or hosts to the custom allowlist in this repository's [Copilot coding agent settings](https://github.com/langgenius/dify/settings/copilot/coding_agent) (admins only) > > </details> <!-- START COPILOT CODING AGENT SUFFIX --> <details> <summary>Original prompt</summary> > > ---- > > *This section details on the original issue you should resolve* > > <issue_title>[Chore/Refactor] using lazy initial</issue_title> > <issue_description>### Self Checks > > - [x] I have read the [Contributing Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md) and [Language Policy](https://github.com/langgenius/dify/issues/1542). > - [x] This is only for refactoring, if you would like to ask a question, please head to [Discussions](https://github.com/langgenius/dify/discussions/categories/general). > - [x] I have searched for existing issues [search for existing issues](https://github.com/langgenius/dify/issues), including closed ones. > - [x] I confirm that I am using English to submit this report, otherwise it will be closed. > - [x] 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :) > - [x] Please do not modify this template :) and fill in all the required fields. > > ### Description > > To prevent re-computation, consider using lazy initial state for useState calls that involve function calls. > > ### Motivation > > To prevent re-computation. > > ### Additional Context > > https://eslint-react.xyz/docs/rules/hooks-extra-prefer-use-state-lazy-initialization</issue_description> > > ## Comments on the Issue (you are @copilot in this section) > > <comments> > </comments> > </details> Fixes langgenius/dify#25213 <!-- START COPILOT CODING AGENT TIPS --> --- 💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click [here](https://survey3.medallia.com/?EAHeSx-AP01bZqG0Ld9QLQ) to start the survey.
yindo added the pull-request label 2026-02-21 20:49:20 -05:00
yindo closed this issue 2026-02-21 20:49:21 -05:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: langgenius/dify#31375