Create components whose prop changes map to a global side effect.
Installation
npm install --save react-side-effect
As a script tag
Development
Production
Use Cases
- Setting
document.body.style.margin
or background color depending on current screen; - Firing Flux actions using declarative API depending on current screen;
- Some crazy stuff I haven't thought about.
componentDidUpdate
?
How's That Different from It gathers current props across the whole tree before passing them to side effect. For example, this allows you to create <BodyStyle style>
component like this:
// RootComponent.jsreturn <BodyStyle => thisstatesomething ? <SomeComponent /> : <OtherComponent /> </BodyStyle>; // SomeComponent.jsreturn <BodyStyle => <div>Choose color: <input = /></div> </BodyStyle>;
and let the effect handler merge style
from different level of nesting with innermost winning:
;;; { return Children; } BodyStylepropTypes = style: PropTypesobjectisRequired; { var style = {}; propsList; return style;} { Object;} reducePropsToState handleStateChangeOnClientBodyStyle;
On the server, you’ll be able to call BodyStyle.peek()
to get the current state, and BodyStyle.rewind()
to reset for each next request. The handleStateChangeOnClient
will only be called on the client.
API
withSideEffect: (reducePropsToState, handleStateChangeOnClient, [mapStateOnServer]) -> ReactComponent -> ReactComponent
A higher-order component that, when mounting, unmounting or receiving new props, calls reducePropsToState
with props
of each mounted instance. It is up to you to return some state aggregated from these props.
On the client, every time the returned component is (un)mounted or its props change, reducePropsToState
will be called, and the recalculated state will be passed to handleStateChangeOnClient
where you may use it to trigger a side effect.
On the server, handleStateChangeOnClient
will not be called. You will still be able to call the static rewind()
method on the returned component class to retrieve the current state after a renderToString()
call. If you forget to call rewind()
right after renderToString()
, the internal instance stack will keep growing, resulting in a memory leak and incorrect information. You must call rewind()
after every renderToString()
call on the server.
For testing, you may use a static peek()
method available on the returned component. It lets you get the current state without resetting the mounted instance stack. Don’t use it for anything other than testing.
Usage
Here's how to implement React Document Title (both client and server side) using React Side Effect:
;;; { if thispropschildren return Children; else return null; } DocumentTitlepropTypes = title: PropTypesstringisRequired; { var innermostProps = propsListpropsListlength - 1; if innermostProps return innermostPropstitle; } { documenttitle = title || '';} reducePropsToState handleStateChangeOnClientDocumentTitle;