react-remount-component
The Problem
You want a React component to reset state when certain props change. Without this library you can do this:
- Class components: implement
getDerivedStateFromProps
andcomponentDidUpdate
to track and respond to props changes - Function components: use a state hook with a cache of previous props to manually call the
set
function of related state hooks - Either: rely on consumers to pass a
key
. This can't be enforced and removes control over internal state from the library.
This Solution
react-remount-component
is a higher-order component that takes a comparison function for new props and previous props. Returning true
from the comparison remounts the component.
Currently, the HOC generates a random key for the wrapped component when a reset is requested. This is an implementation detail that may change in the future.
Usage
Class Component
See usage.test.js
Component state = expanded: false ; { const user = thisprops; return <div ="user-card"> <Name = /> <button => Details </button> thisstateexpanded && <React.Fragment> <Date = /> <Avatar = /> </React.Fragment> </div> ; } UserCard props prevProps const prevUserId = prevPropsuser && prevPropsuserid; const nextUserId = propsuser && propsuserid; if nextUserId !== prevUserId return true; // remount! return false; // don't remount otherwise;
Function Component
{ const user = props; const isExpanded setExpanded = React; return <div ="user-card"> <div>Name: username</div> <div> <button => See Details </button> </div> isExpanded && <React.Fragment> <div>Birthday: userbirthDate</div> <div>Favorite Color: userfavoriteColor</div> </React.Fragment> </div> ;} UserCard props prevProps const prevUserId = prevPropsuser && prevPropsuserid; const nextUserId = propsuser && propsuserid; if nextUserId !== prevUserId return true; // remount! return false; // don't remount otherwise;
React RFC
https://github.com/reactjs/rfcs/pull/62