Proposal is to allow creating lazy inlined global constants.
It will allow to make more performant, compact and less fragmentized code, and will help to avoid some common issues like in Example 2.
Example 1
// Bad: array is created on each call
const doSomething = () => {
if (["a", "b", "c"].includes(x)) {
...
}
}
// Good: array is created lazily once and stored as global constant
const doSomething = () => {
if (@["a", "b", "c"].includes(x)) {
...
}
}
Example 2
const selector = (state) => {
// Bad: selector is not pure, it returns different empty array each time,
// which causes re-render on each state change
if (!state.items) {
return []
}
...
// Good: always returns the same empty array,
// created lazily as global constant
if (!state.items) {
return @[]
}
}
Example 3
// Bad: styles are created on app launch, which slows the app launch
const styles = StyleSheet.create({
container: {
...
}
})
// Good: styles are not created here yet
lazy const styles = StyleSheet.create({
container: {
...
}
})
const Component = () => {
// they are lazily created when accessed for the first time
return <App style={styles.container}/>
}
// another version
@const styles =...
Example 4
// Bad: default options are created on each function call,
// or it requires creating constant explicitly outside, which requires
// more time and over-fragmentize the function code.
const doSomething = (options) => {
if (!options) {
options = {
isDev: true,
}
}
}
// Good: default options are created lazily once and stored
// as a global constant, code is not fragmentized.
const doSomething = (options) => {
if (!options) {
options = @{
isDev: true,
}
}
}
Example 5
// Bad: creating keyExtractor on each render call ruins
// memoization of MemoizedComponent (React)
const Component = (props) => {
return (
<MemoizedComponent
keyExtractor={(item) => item.id}
...
/>
)
}
// Good: keyExtractor is created lazily once as a global constant,
// without useCallback or code fragmentation
const Component = (props) => {
return (
<MemoizedComponent
keyExtractor={@(item) => item.id}
...
/>
)
}
Example 6
const doSomething = (array) => {
// Bad: it is a good practise to move some code to a separate
// scope without fragmentation to different functions,
// but here function is created on each call.
const values = (() => {
const a = ...
const b = ...
const y = ...
...
return array.filter(x => x !== y)
})()
// Good: function is created globally once, lazily,
// and its previous closure is passed as usual argument
const values = (@() => {
const a = ...
const b = ...
const y = ...
...
return array.filter(x => x !== y)
})()
}