final-form / final-form/react-final-form

Suggestion: Create `useCalculatedFieldValue` to avoid unnecessary re-renders for calculated fields

Open
#643 1 comment 3 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
7.4k
Forks
497
PR merge metrics
No merged PRs in 30d

Description

### Are you submitting a **bug report** or a **feature request**?

Feature request

### What is the current behavior?

Currently, if we want a calculated value from a field name, the `useField` will trigger any time the field changes. In cases where we `useField` on an array and may only want to retrieve calculated count or specific filtered indices, these extra rerenders are detrimental and also cause fields to lose focus.

### What is the expected behavior?

Expose a new hook to only trigger a new render when the calculated value changes instead of every time any inner value changes.

### Sandbox

Here is a code sandbox of a workaround my team is using:

https://codesandbox.io/s/kind-jang-m62pd

```ts
function SyncCalculatedValue({ calculate, name, onChange }) {
const { input } = useField(name);
const { value } = input;
const calculatedValue = calculate(value);
const prev = usePrevious(calculatedValue);

useEffect(() => {
if (calculatedValue !== prev) {
onChange(calculatedValue);
}
}, [calculatedValue, prev, onChange]);

return null;
}
```

```ts
function Count2() {
const [numFields, setNumFields] = useState(undefined);

console.log("rendering Count2");

return (
<>
{
if (!Array.isArray(testFields)) {
return 0;
}

return testFields.length;
}}
onChange={setNumFields}
/>
Count2: {numFields}

);
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.