react-remountable
- provides an API
remount
as prop for re-mounting component - resets stateful component to initial state
- just use it like using the
ReactComponent::forceUpdate
API - re-calls phases:
componentWillUnmount
->constructor
->static getDerivedStateFromProps(v16.3+)
->render
-> collect refs ->componentDidMount
Why
We may need:
- Refresh a component locally
- Discard the mutated state data
- Trigger some component life-cycle hooks
Installation
yarn add react-remountable
or
npm install -s react-remountable
Example:
import remountable from 'react-remountable'import StatefulForm1 StatefulForm2 StatefulForm3 from './Forms' @remountable // decorator syntaxComponent state = greeting: '' whatsUp: '' ref && ref { this } { // 1. send log // 2. re-render/refresh Dashboard component and its stateful children components // 3. auto focus on the text input // 4. fetch today's greeting and render it thisprops } async { const greeting = await this } { return <div> <h1>thisstategreeting</h1> <StatefulForm1 /> <StatefulForm2 /> <StatefulForm3 /> <input = = /> <button =>Reset</button> </div> } { }
If the ESNext decorator syntax is not enabled:
Dashboard