{"library":"react-lifecycles-compat","title":"React Lifecycles Compatibility Polyfill","description":"`react-lifecycles-compat` is a JavaScript polyfill designed to provide backwards compatibility for React class components. It enables the use of the `static getDerivedStateFromProps` and `getSnapshotBeforeUpdate` lifecycles (introduced in React 16.3) with older versions of React, specifically 0.14.9+. This functionality was critical for libraries and applications during the transition period when React deprecated `componentWillMount`, `componentWillReceiveProps`, and `componentWillUpdate` due to issues with async rendering. By using this polyfill, developers could adopt the newer, safer lifecycles without forcing users of older React versions to upgrade their entire React setup, thus facilitating a smoother ecosystem transition. The package is currently at version 3.0.4. While still functional, its primary relevance has diminished significantly with the widespread adoption of modern React versions (17+) and the prevalence of React Hooks.","language":"javascript","status":"maintenance","last_verified":"Sun Apr 19","install":{"commands":["npm install react-lifecycles-compat"],"cli":null},"imports":["import { polyfill } from 'react-lifecycles-compat';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import React from 'react';\nimport { polyfill } from 'react-lifecycles-compat';\n\nclass ExampleComponent extends React.Component {\n  static getDerivedStateFromProps(nextProps, prevState) {\n    // This method works with React 16.3+ natively,\n    // and with older React versions (0.14.9+) after polyfilling.\n    if (nextProps.value !== prevState.internalValue) {\n      return { internalValue: nextProps.value };\n    }\n    return null;\n  }\n\n  constructor(props) {\n    super(props);\n    this.state = { internalValue: props.value, scrollPos: 0 };\n    this.listRef = React.createRef();\n  }\n\n  getSnapshotBeforeUpdate(prevProps, prevState) {\n    // Captures scroll position before DOM update\n    if (this.listRef.current) {\n      return this.listRef.current.scrollTop;\n    }\n    return null;\n  }\n\n  componentDidUpdate(prevProps, prevState, snapshot) {\n    // Use snapshot to restore scroll position\n    if (snapshot !== null && this.listRef.current) {\n      this.listRef.current.scrollTop = snapshot;\n    }\n  }\n\n  render() {\n    return (\n      <div ref={this.listRef} style={{ height: '200px', overflow: 'auto' }}>\n        <h1>Value: {this.state.internalValue}</h1>\n        <p>Scrollable content...</p>\n      </div>\n    );\n  }\n}\n\n// Apply the polyfill to make new lifecycles work with older React versions\npolyfill(ExampleComponent);\n\nexport default ExampleComponent;","lang":"javascript","description":"Demonstrates applying the `polyfill` to a React class component using `getDerivedStateFromProps` and `getSnapshotBeforeUpdate`.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}