or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# React LazyLoad

1

2

React LazyLoad is a high-performance React component for lazy loading that improves application performance by loading content only when it enters the viewport. It provides efficient viewport detection using only two global event listeners regardless of the number of lazy-loaded components, supports both one-time and continuous lazy loading modes, offers configurable offset values for preloading elements before they become visible, includes throttling and debouncing for scroll events, and provides decorator syntax for easy integration with existing components.

3

4

## Package Information

5

6

- **Package Name**: react-lazyload

7

- **Package Type**: npm

8

- **Language**: JavaScript (React component library)

9

- **Installation**: `npm install react-lazyload`

10

11

## Core Imports

12

13

```javascript

14

import LazyLoad from 'react-lazyload';

15

```

16

17

For decorator support:

18

19

```javascript

20

import LazyLoad, { lazyload } from 'react-lazyload';

21

```

22

23

For utility functions:

24

25

```javascript

26

import LazyLoad, { forceCheck, forceVisible } from 'react-lazyload';

27

```

28

29

CommonJS:

30

31

```javascript

32

const LazyLoad = require('react-lazyload');

33

const { lazyload, forceCheck, forceVisible } = require('react-lazyload');

34

```

35

36

## Basic Usage

37

38

```javascript

39

import React from 'react';

40

import LazyLoad from 'react-lazyload';

41

42

const App = () => {

43

return (

44

<div className="list">

45

{/* Basic lazy loading */}

46

<LazyLoad height={200}>

47

<img src="image1.jpg" alt="Lazy loaded image" />

48

</LazyLoad>

49

50

{/* One-time lazy loading */}

51

<LazyLoad height={200} once>

52

<MyComponent />

53

</LazyLoad>

54

55

{/* Preload when 100px from viewport */}

56

<LazyLoad height={200} offset={100}>

57

<MyComponent />

58

</LazyLoad>

59

60

{/* With custom placeholder */}

61

<LazyLoad height={200} placeholder={<div>Loading...</div>}>

62

<MyComponent />

63

</LazyLoad>

64

</div>

65

);

66

};

67

```

68

69

## Architecture

70

71

React LazyLoad is built around several key components:

72

73

- **LazyLoad Component**: The main wrapper component that handles visibility detection and content rendering

74

- **Global Event Management**: Uses only two global event listeners (scroll/resize) for all LazyLoad instances for optimal performance

75

- **Viewport Detection**: Efficient algorithms for detecting when elements enter/exit the viewport, including support for overflow containers

76

- **Decorator Pattern**: Higher-order component decorator for seamless integration with existing components

77

- **Manual Control**: Utility functions for programmatic control over lazy loading behavior

78

79

## Capabilities

80

81

### LazyLoad Component

82

83

The main React component that wraps content and loads it only when visible in the viewport.

84

85

```javascript { .api }

86

/**

87

* LazyLoad wrapper component for lazy loading content

88

* @param {React.ComponentProps<typeof LazyLoad>} props - Component props

89

* @returns {React.ReactElement} LazyLoad wrapper element

90

*/

91

function LazyLoad(props: LazyLoadProps): React.ReactElement;

92

93

interface LazyLoadProps {

94

/** The content to lazy load (only one child allowed) */

95

children: React.ReactNode;

96

/** Placeholder height for initial render, can be number or string like '100%' */

97

height?: number | string;

98

/** Whether to stop observing after first load */

99

once?: boolean;

100

/** Viewport offset for triggering load, number or [horizontal, vertical] array */

101

offset?: number | [number, number];

102

/** Whether component is in overflow container */

103

overflow?: boolean;

104

/** Whether to listen to resize events */

105

resize?: boolean;

106

/** Whether to listen to scroll events */

107

scroll?: boolean;

108

/** Throttle delay for scroll/resize handlers in milliseconds */

109

throttle?: number | boolean;

110

/** Debounce delay for scroll/resize handlers in milliseconds */

111

debounce?: number | boolean;

112

/** Custom placeholder element to show before loading */

113

placeholder?: React.ReactNode;

114

/** Custom scroll container selector string or DOM element */

115

scrollContainer?: string | HTMLElement;

116

/** Whether to unmount when not visible */

117

unmountIfInvisible?: boolean;

118

/** CSS class for wrapper element */

119

className?: string;

120

/** Prefix for generated CSS classes */

121

classNamePrefix?: string;

122

/** Inline styles for wrapper element */

123

style?: React.CSSProperties;

124

}

125

```

126

127

**Default Props:**

128

- `className`: `''`

129

- `classNamePrefix`: `'lazyload'`

130

- `once`: `false`

131

- `offset`: `0`

132

- `overflow`: `false`

133

- `resize`: `false`

134

- `scroll`: `true`

135

- `unmountIfInvisible`: `false`

136

137

**Usage Examples:**

138

139

```javascript

140

// Basic image lazy loading

141

<LazyLoad height={200}>

142

<img src="tiger.jpg" alt="Tiger" />

143

</LazyLoad>

144

145

// One-time loading with offset

146

<LazyLoad height={200} once offset={100}>

147

<ExpensiveComponent />

148

</LazyLoad>

149

150

// Overflow container support

151

<LazyLoad overflow>

152

<div>Content in scrollable container</div>

153

</LazyLoad>

154

155

// Custom placeholder

156

<LazyLoad placeholder={<div className="spinner">Loading...</div>}>

157

<MyComponent />

158

</LazyLoad>

159

160

// Performance optimization with debouncing

161

<LazyLoad debounce={300}>

162

<HeavyComponent />

163

</LazyLoad>

164

```

165

166

### Decorator Function

167

168

Higher-order component decorator that wraps components with LazyLoad functionality.

169

170

```javascript { .api }

171

/**

172

* Decorator function for lazy loading components

173

* @param {LazyLoadProps} options - LazyLoad options to apply

174

* @returns {function} Higher-order component function

175

*/

176

function lazyload(options?: Partial<LazyLoadProps>): (WrappedComponent: React.ComponentType) => React.ComponentType;

177

```

178

179

**Usage Examples:**

180

181

```javascript

182

import { lazyload } from 'react-lazyload';

183

184

// ES6 decorator syntax

185

@lazyload({

186

height: 200,

187

once: true,

188

offset: 100

189

})

190

class MyComponent extends React.Component {

191

render() {

192

return <div>This component is lazyloaded by default!</div>;

193

}

194

}

195

196

// Function syntax

197

const LazyMyComponent = lazyload({

198

height: 200,

199

once: true

200

})(MyComponent);

201

```

202

203

### Manual Visibility Control

204

205

#### forceCheck

206

207

Manually triggers visibility checking for all registered LazyLoad components.

208

209

```javascript { .api }

210

/**

211

* Forces a visibility check for all LazyLoad components

212

* Useful when components enter viewport without scroll/resize events

213

*/

214

function forceCheck(): void;

215

```

216

217

**Usage Examples:**

218

219

```javascript

220

import { forceCheck } from 'react-lazyload';

221

222

// After showing a hidden container

223

const showModal = () => {

224

setModalVisible(true);

225

// Force check since components became visible without scroll

226

forceCheck();

227

};

228

229

// After dynamic content insertion

230

const addContent = () => {

231

setItems([...items, newItem]);

232

setTimeout(forceCheck, 0); // Check after DOM update

233

};

234

```

235

236

#### forceVisible

237

238

Forces all LazyLoad components to display regardless of viewport visibility.

239

240

```javascript { .api }

241

/**

242

* Forces all LazyLoad components to display regardless of visibility

243

* Useful for printing or full content display

244

*/

245

function forceVisible(): void;

246

```

247

248

**Usage Examples:**

249

250

```javascript

251

import { forceVisible } from 'react-lazyload';

252

253

// Before printing

254

const handlePrint = () => {

255

forceVisible(); // Load all content for printing

256

setTimeout(() => window.print(), 100);

257

};

258

259

// For accessibility or full content display

260

const showAllContent = () => {

261

forceVisible();

262

setShowAllMode(true);

263

};

264

```

265

266

## Advanced Usage Patterns

267

268

### Overflow Container Support

269

270

For lazy loading within scrollable containers:

271

272

```javascript

273

// CSS: Ensure container has position other than static

274

.scroll-container {

275

height: 400px;

276

overflow-y: auto;

277

position: relative; /* Required for overflow detection */

278

}

279

280

// React component

281

<div className="scroll-container">

282

<LazyLoad height={200} overflow>

283

<MyComponent />

284

</LazyLoad>

285

</div>

286

```

287

288

### Performance Optimization

289

290

```javascript

291

// Throttle scroll events (limits to every 300ms)

292

<LazyLoad throttle={300}>

293

<MyComponent />

294

</LazyLoad>

295

296

// Debounce scroll events (waits 300ms after scroll stops)

297

<LazyLoad debounce={300}>

298

<MyComponent />

299

</LazyLoad>

300

301

// Use boolean for default timing (300ms)

302

<LazyLoad throttle>

303

<MyComponent />

304

</LazyLoad>

305

```

306

307

### Custom Scroll Container

308

309

```javascript

310

// String selector

311

<LazyLoad scrollContainer=".custom-scroll">

312

<MyComponent />

313

</LazyLoad>

314

315

// DOM element reference

316

const scrollElement = useRef();

317

<LazyLoad scrollContainer={scrollElement.current}>

318

<MyComponent />

319

</LazyLoad>

320

```

321

322

### Offset Configuration

323

324

```javascript

325

// Single number applies to all directions

326

<LazyLoad offset={100}> {/* 100px offset in all directions */}

327

<MyComponent />

328

</LazyLoad>

329

330

// Array format: [horizontal, vertical]

331

<LazyLoad offset={[50, 100]}> {/* 50px horizontal, 100px vertical */}

332

<MyComponent />

333

</LazyLoad>

334

335

// Negative offset delays loading

336

<LazyLoad offset={-50}> {/* Load 50px after entering viewport */}

337

<MyComponent />

338

</LazyLoad>

339

```

340

341

### Unmounting Invisible Content

342

343

```javascript

344

// Unmount component when not visible (saves memory)

345

<LazyLoad unmountIfInvisible>

346

<ExpensiveComponent />

347

</LazyLoad>

348

```

349

350

## Error Handling

351

352

React LazyLoad handles errors gracefully:

353

354

- **Invalid DOM elements**: Safely handles cases where refs don't point to HTML elements

355

- **getBoundingClientRect errors**: Falls back to default positioning when DOM methods fail

356

- **Event listener failures**: Degrades gracefully when passive events aren't supported

357

358

## Browser Compatibility

359

360

- **Modern browsers**: Full support with passive event listeners for optimal performance

361

- **Legacy browsers**: Automatic fallback to standard event listeners

362

- **Server-side rendering**: Safe to use with SSR, gracefully handles missing window object

363

- **Internet Explorer**: Compatible with proper polyfills for getBoundingClientRect

364

365

## Performance Characteristics

366

367

- **Memory efficient**: Only 2 global event listeners regardless of component count

368

- **CPU optimized**: Efficient viewport detection algorithms

369

- **Network friendly**: Loads content only when needed

370

- **Scroll performance**: Uses passive events and optional throttling/debouncing

371

- **Cleanup**: Automatic listener removal on component unmount