Prevent Re-Render when React Element passed as Prop - reactjs

In my React app, I am using a few libraries (i.e. Material UI and React Intl) to pass React elements as props from higher-level components down to "dumb components" that have one job: to render.
Smart component:
import ActionExplore from 'material-ui/svg-icons/action/explore';
import { FormattedMessage } from 'react-intl';
export class SmartComponent extends Component {
render() {
return (
<div>
<DumbComponent
text={<FormattedMessage id="en.dumbComponent.text" />}
icon={<ActionExplore/>}
/>
<AnotherDumbComponent {props.that.are.changing} />
</div>
);
}
}
Dumb component:
import shallowCompare from 'react-addons-shallow-compare';
export class DumbComponent extends Component {
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
render() {
return (
<div>
<h1>{this.props.text}</h1>
{this.props.icon}
</div>
);
}
}
The benefit of doing this, is that the DumbComponent does not need to know anything about application logic (material ui, internationalization, etc.). It simply renders, leaving SmartComponent to take care of all the business logic.
The downside I am encountering with this approach is performance: DumbComponent will always re-render, even when AnotherDumbComponent's props change instead of its own, because shouldComponentUpdate always returns true. shouldComponentUpdate is unable to do an accurate equality check between React elements in the above example.
How can React elements be equality-checked in shouldComponentUpdate? Is this too costly to perform? Is passing React elements as props to dumb components a bad idea? Is it possible to not pass down React elements as props, yet keep components dumb? Thanks!

Whether it is performant or not is going to depend on your use case. As a rule of thumb, I think this kind of logic is best used when you expect user input to only impact children of the "dumb component", rather than it's peers.
As an example, Material-UI's Dialog has almost identical structure to what you suggest for it's action buttons and title. (https://github.com/callemall/material-ui/blob/master/src/Dialog/Dialog.js#L292). But it works well in that case because those elements are on the modal, which itself doesn't modify unless you are opening or closing it.
As another potential workaround, what if you passed in the objects needed to create the children elements, without passing in the entire element? I haven't tried this, so I'm not sure how well it will work, but it might be worth a try. Something to the extent of;
<DumbComponent
textComponent={FormattedMessage}
textProps={{id: "en.dumbComponent.text"}}/>
//In DumbComponent;
render(){
return (
<div>
<h1>
<this.props.textComponent {...this.props.textProps}/>
</h1>
</div>
);
}
Might give you some more concrete things to play around with when determining if you should update or not.

I solved this by converting these plain React elements into Immutable.js maps, and passing those as props instead.
This article was very helpful: https://www.toptal.com/react/react-redux-and-immutablejs
Immutable.js allows us to detect changes in JavaScript objects/arrays without resorting to the inefficiencies of deep equality checks, which in turn allows React to avoid expensive re-render operations when they are not required.

Related

Why Reactjs has to reuse code in HOC?

All I want is to run a piece of javascript code to query back-end GraphQL server. Why do I have to wrap my query in a HOC component? Like it says in this document.
import { Query } from "react-apollo";
import gql from "graphql-tag";
const ExchangeRates = () => (
<Query
query={gql`
{
rates(currency: "USD") {
currency
rate
}
}
`}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.rates.map(({ currency, rate }) => (
<div key={currency}>
<p>{`${currency}: ${rate}`}</p>
</div>
));
}}
</Query>
);
It looks like a very clumsy awkward solution? Why it has to be this way? Does it make things easier or more difficult? What is the philosophy behind it?
Update:
One thing trouble a lot is: I just want to make an API call, which is not visible, why do I have to render a tag inside render() function? API call are not supposed to be visible at all. This twist make me feel this whole HOC thing is a hack, bogus. What do you think?
They use Render Prop Pattern because of it's highly declarative nature as outlined here
This encapsulation makes composing your Query components with your presentational components a breeze
Now about the Render Prop itself, as per official react docs
The term “render prop” refers to a simple technique for sharing code between React components using a prop whose value is a function.
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
As described here this technique is React's favoured way of handling cross-cutting concerns.
Components are the primary unit of code reuse in React, but it’s not a always obvious how to share the state or behavior that one component encapsulates to other components that need that same state.
So with render prop you put out only the public outcome of your encapsulated state that you want to share with other components.
render prop is not HoC, but is an alternative to it, that was recently embraced by the react team itself.

What's render props, how is it different from high order components?

It seems render props have not get enough traction so far, however, it's widely used by prestigious react libraries, like react-router 4, react motion etc. And react site also have a dedicated section for it, any reason for this emerged pattern, how is compared to commonly known HOC (high order component) pattern?
Leave an answer for my research, different answers & discussions are highly welcome!
HOC borrows the concept from High Order Function:
a higher-order function (also functional, functional form or functor) is a function that does at least one of the following:
takes one or more functions as arguments (i.e., procedural parameters),
returns a function as its result.[disputed – discuss]
HOC
A higher-order component (HOC) is an advanced technique in React for reusing component logic.
Originates from this Gist.
This pattern is about STATIC composition. Core/reusable logic are encapsulated in the HOC, while leaving the moving parts to the component.
Use withRouter from react router as an example:
withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.
// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))
Now you get an enhanced MyComponent back which has the props of { history, match, location, ...connectProps, ...ownProps } passed by the router HOC.
A common approach is to
compose(
connect( ... ),
enhance( ... ),
withRouter( ... ),
lifecycle( ... ),
somethingElse( ... )
)(MyComponent);
The great part is that you can infinitely compose those HOCs with a compose utility to get a final enhanced version of your component, and your component will get knowledge about redux store, react router etc injected from the new component returned by HOC.
The downside of the approach is that:
The behavior of the component is defined before runtime thus lost the power of react's rendering lifecycles, say you can't do something like:
compose(
this.state.shouldConnect && connect( ... ),
this.state.shouldEnhance && enhance( ... ),
this.state.shouldWithRouter && withRouter( ... ),
...
)(MyComponent);
since state/props is not available before your code runs.
Indirection & Naming collisions.
using a HOC with ES6 classes poses many of the same problems that mixins did with createClass, just re-arranged a bit.
HOCs introduce a lot of ceremony due to the fact that they wrap components and create new ones instead of being mixed in to existing components.
Render Props
A render prop is a function prop that a component uses to know what to render.
First adopted by react-motion, early seen in Dan's Gist few weeks before first commit of redux.
This pattern is about DYNAMIC composition. Core/reusable logics stays in the component while the moving parts get passed as a callback prop.
You can create HOCs through render props.
Still use withRouter as an example:
const withRouter = Component => {
const C = props => {
const { wrappedComponentRef, ...remainingProps } = props;
return (
<Route
render={routeComponentProps => (
<Component
{...remainingProps}
{...routeComponentProps}
ref={wrappedComponentRef}
/>
)}
/>
);
};
...
return hoistStatics(C, Component);
};
While the opposite is not true.
<Connect render={connectPropsMergedWithState => {
<Enhance render={enhancePropsMergedWithState => {
<WithRouter render={routerPropsMergedWithState => {
<Lifecycle render={lifecyclePropsMergedWithState => {
<SomethingElse render={somethingElsePropsMergedWithState => {
...
}/>
...
}/>
...
}/>
...
}/>
...
}/>
Though it might look not so good, it has lots of gains.
It has better explicitness, since we can see what's exactly passed as parameter to the render props.
Because of 1, it saves us from potential props collisions.
It's dynamic, we can pass whatever we like (including state/props) to render props.
The commonly known downside is performance optimization is tricky, since what props to receive is deferred to runtime. And it's probably not a good idea to do any premature optimization, but that might be totally another topic.
If you agreed upon the direction move of react router from 3 to 4, render props might be your jam.
References:
https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce
https://reactrocket.com/post/turn-your-hocs-into-render-prop-components

How does one React component call a method in another React component?

My page contains two completely separate React components (different files, different classes, no parent-child relationship).
How can one component call an instance method in another component? The problem seems to be obtaining the instance of the target component.
EDIT: Both components share the same parent (i.e. they are rendered in the same render() method) but I still don't know how to pass the reference of the target component to the calling component.
The short answer is: they don't.
It's not clear what you're trying to accomplish, so I can't speak to the specifics of your case, but the way React components "communicate" with one another is via state and props. For example, consider a Page component that has two child components, CompA and CompB, rendered something like this:
<Page>
<CompA />
<CompB />
</Page>
If CompA needs to pass something to CompB, this is done through state on the Page component, with that state exposed as props on CompA and CompB, something like this:
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
sharedValue: 42,
};
}
onChangeSharedValue(newValue) {
this.setState({ sharedValue: newValue });
}
render() {
return (
<div>
<CompA
sharedValue={this.state.sharedValue}
onChange={this.onChangeSharedValue}
/>
<CompB
sharedValue={this.state.sharedValue}
onChange={this.onChangeSharedValue}
/>
</div>
);
}
}
If CompA needs to change the shared value, it calls the onChange handler, which will change the state on the Page component. That value will then be propagated down to the CompB component.
There is no direct communication between components like you're describing; it is all done via state and props.
"Props down, Events up."
If you provide us a specific example of what you're looking for, I can update this post with a more specific response.
But in general, there are a couple of strategies that you can take. Some of them are presented here.
The preferred approach is to simply move your calling method to the parent component. It's a common strategy in React.
If you're not able to, then the next step would be to write an event handler for the parent, and then pass this event down to the first child component.
Use this event to pass information up to the parent, so that when it gets triggered, data can be passed as props down to the second component.
I only recently started doing React development and I found a solution for this problem that suits me. Admittedly, I haven't seen it referenced anywhere and when I showed it to a colleague who's been doing React for years, he kinda furrowed his brow and felt that it wasn't "right", but he couldn't really articulate to me why it's "wrong". I'm sure I'll be shouted down for it here, but I thought I'd share anyway:
File #1: objects.js
let objects= {};
export default objects;
File #2: firstComponent.js
import React from 'react';
import objects from 'objects';
class FirstComponent extends React.Component {
constructor(props) {
super(props);
objects['FirstComponent'] = this; // store a reference to this component in 'objects'
}
doSomethingInFirstComponent() {
console.log('did something in first component');
}
render() {
return (<div></div>);
}
}
export default FirstComponent;
File #3: secondComponent.js
import React from 'react';
import objects from 'objects';
class SecondComponent extends React.Component {
render() {
objects.FirstComponent.doSomethingInFirstComponent(); // call the method on the component referred to in 'objects'
return (<div></div>);
}
}
export default SecondComponent ;
When SecondComponent renders, it will trigger the console.log() in FirstComponent.doSomethingInFirstComponent(). This assumes, of course, that FirstComponent is actually mounted.
The "React Guys" that I know seem to think this approach is somehow evil. It uses a simple JavaScript object outside the normal React scope to maintain a reference to any existing objects that I choose to store there. Other than them telling me that "this isn't the way you do things in React", I haven't yet found a good explanation for how this will break or otherwise screw-up my app. I use it as a low-grade replacement for massive-overkill state-management tools like Redux. I also use it to avoid having to pass properties down through dozens of layers of React components just so something at the last level can trigger something waaaaay up in the first level.
That's not to say this approach doesn't have it's problems:
It creates an obvious dependency between the generic objects object, any component that is designed to store a reference to itself inside objects, and any component that wishes to utilizes those references. Then again, using any kind of global state-management solution creates a similar dependency.
It's probably a bad solution if you have any doubt that FirstComponent will be mounted before you try to call it from within SecondComponent.
I've found that just having the reference to a React component won't allow you to do all the things that React components can do natively. For example, it won't work to call objects.FirstComponent.setState(). You can call a method in FirstComponent, which in turn can invoke its own setState(), but you can't invoke FirstComponent's setState() directly from within SecondComponent. Quite frankly, I think this is a good thing.
You can, however, directly access the state values from the components referenced in objects.
This should only be done with "global" components (components that functionally serve as singletons). If, for example, you had a simple UI component called BasicSpan that did little more than render a basic span tag, and you proceeded to use that component over and over again throughout your React app, I'm sure it would quickly become an unmanageable nightmare to try to place references to these simple components in the objects object and then try to intelligently manage calls to those components' internal methods.
you can send an event as props and call it from other component.
Say you have a class
Class A{
handleChange(evt)
{
this.setState({
name:evt.target.value
})
}
render{
return(
<div>
<ComponentB name={this.state.name}{ onChange={this.handleChange}/>
</div>
);
}
}
Child Component
Class B{
handleChange()
{
//logic
}
render{
return(
<div>
<input type="text" onChange={this.props.onChange}/>
{this.props.name}
</div>
);
}
Here in Component B when you change the input it will call the method
of class A and update state of A.
Now getting the updated state as props in component B will give you
the changed text that you just entered

How can I find all nested Components using React/Redux?

I am looking to validate a form with Redux. I am trying to use make a form component which will iterate through children and find various input components (not to be confused with a native <input>.
I know there are a lot of open source solutions, but I'd like to understand some mechanics before jumping into picking any. I have a Form component setup to test like this:
import React from 'react';
export default class Component extends React.Component {
componentDidMount() {
this._iterate(this.props.children);
}
render(){
return (
<form {...this.props}>{this.props.children}</form>
);
}
_iterate(children) {
React.Children.forEach(children, child => {
console.log(child);
if (child.props.children) {
console.log('get children');
this._iterate(child.props.children);
}
});
}
};
I then have another Component with a render like this:
render() {
return (
<div>
<Form>
<ComponentA />
<ComponentB />
</Form>
</div>
);
}
Now ComponentA or ComponentB might have a component that nests more components down the line. Within those components would be a React component I have made for Text, Select, etc.
The code above would just console.log the components, and any children of them, that are in this specific render. It does not jump down into ComponentA children.
Is there a solution to that?
This isn't a problem you really want to solve.
The power in react is largely around the design pattern it encourages, and what you're doing is breaking that pattern; Component's should only talk to their immediate children and respond to their immediate parents. If you need to go deeper than that, then the component in the middle needs to be responsible for passing that data.
Rather than trying to dig into the innards of ComponentA and ComponentB, those component's themselves should have the accessibility props that you need. I.e., <ComponentA onChange={whatever} errorMessage={whatever}/> etc. and then hooking those props to their children should occur within ComponentA.

Should React lifecycle methods be implemented in container components or presentation components?

I'm attempting to implement container components in React and Redux, and I'm unsure of what should take responsibility for lifecycle methods; containers or presentational components. One could argue that the lifecycle methods are presentational as they control DOM updates, but in that respect, aren't they also behavioural?
Furthermore, all of the implementations of container components that I've seen thus far utilise the react-redux bindings, as do my own. Even if I keep the concerns clearly separated, is it appropriate to inherit from React.Component in the case of a behaviour component?
For example, the app on which I'm working has a Tab presentational component, with a shouldComponentUpdate method:
class Tabs extends Component {
shouldComponentUpdate(nextProps) {
const { activeTab } = this.props;
return activeTab !== nextProps.activeTab;
}
[...]
}
On the one hand, this seems like a presentational concern as it controls when component should re-render. On the other hand, however, this is a means of handling when the user clicks a new tab, updating the application's state via an action, thus I'd class this as behavioural.
Data should be controlled as close to the root of the tree as possible. Doing this provides some simple optimizations, being that you're only passing what you need.
This will bubble down to where you are controlling some lifecycle components. As mgmcdermott mentioned, a lot of lifecycle components really depend on what you're doing, but the best case scenario is to have the simplest, dumbest components.
In most of my projects, in my react directory, I have components/ and views/. It is always my preference that a view should do as much of the grunt work as possible. That being said, there a a number of components that I've built that use lifecycle methods like componentDidMount, componentWillMount, componentWillUnmount, but I typically try and isolate updates in my views, since one of their jobs, in my opinion, is controlling data flow. That means componentShouldUpdate would live there. Personally, I think componentShouldUpdate is purely end-of-the-line optimization, though, and I only use it in cases where I'm having large performance issues during a re-render.
I'm not super sure I understand your "inherit from React.Component" question. If you're asking whether or not to use pure functions, es6 class, or React.createClass, I don't know that there is a standard rule, but it is good to be consistent.
To address whether or not you are dealing with a behaviour or presentation, behaviour is the click, but re-drawing is presentation. Your behaviour might be well off to exist in your Tab component, where the re-draw in your Tabs view. Tabs view passes your method from redux to set the currently active tab into your individual Tab components, and can then send the behaviour of tab switching through redux so you can do your presentation componentShouldUpdate. Does that make sense?
So your mapToDispatch method in your container will have a function to set your active tab, let's call it activateTab(idx), which takes a 0-based index of the tab. Your container passes that to the containing component that you control, which is views/Tabs, and it passes that method along to components/Tab. components/Tab will have an onClick method which is listening on one of your DOM elements, which then calls this.props.activateTab(myIndex) (you could also pass a bound version of activateTab into components/Tab so it does not have to be aware of it's own index), which triggers redux, then passes back your data into views/Tabs which can handle a componentShouldUpdate based on the data from redux.
Expanded Edit: Since this was marked as accepted, I'll blow out my code example into something usable to the average person.
As a quick aside, I'm not going to write much redux, as this can be very app dependent, but I'm assuming that you have a state with activeTabIdx hanging off the parent.
containers/TabExample.jsx
import { connect } from 'react-redux'
import Tabs from 'views/Tabs.js'
const mapStateToProps = function (state) {
return {
activeTabIdx: state.activeTabIdx
// And whatever else you have...
}
}
const mapDispatchToProps = function (dispatch) {
return {
activateTab: function (idx) {
dispatch({
action: 'ACTIVATE_TAB_IDX',
idx: idx
}) // You probably want this in a separate actions/tabs.js file...
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Tabs)
views/Tabs.js
import React, { createClass } from 'react'
import Tab from 'components/Tab.js'
const { number, func } = React.PropTypes
// Alternatively, you can use es6 classes...
export default createClass({
propTypes: {
activeTabIdx: number.isRequired,
activateTab: func.isRequired
},
render () {
const { activeTabIdx } = this.props
const tabs = ['Tab 1', 'Tab 2', 'Tab 3']
return (
<div className='view__tabs'>
<ol className='tabs'>
{this.renderTabLinks(tabs, activeTabIdx)}
</ol>
</div>
)
},
renderTabLinks (tabs, activeTabIdx) {
return tabs.map((tab, idx) => {
return (
<Tab
onClick={this.props.activateTabIdx.bind(this, idx)}
isActive={idx === activeTabIdx}
>
{tab}
</Tab>
)
})
}
})
components/Tab.js
import React, { createClass } from 'react'
const { func, bool } = React.PropTypes
// Alternatively, you can use es6 classes...
export default createClass({
propTypes: {
children: node.isRequired,
onClick: func.isRequired,
isActive: bool.isRequired
},
handleClick (e) {
const { isActive, onClick } = this.props
e.preventDefault()
if (!isActive) {
onClick()
}
},
render () {
const { children, isActive } = this.props
const tabClass = isActive
? 'tabs__items tabs__items--active'
: 'tabs__items'
return (
<li className={tabClass}>
<a className='tabs__item-link' onClick={this.handleClick}>
{children}
</a>
</li>
)
}
That will mostly do the right thing. Keep in mind that this doesn't handle/care about tab content, and as a result, you may want to structure your view differently.
I think that this is a matter of opinion. I personally like to keep my presentational components as dumb as possible. This allows me to also write most of my presentational components as stateless functions, which are being optimized more and more in React updates. This means that if I can help it, I will prevent any presentational component from having an internal state.
In the case of your example, I don't believe that it is a presentational concern because componentShouldUpdate is a pure function of the props, which should be passed whenever this component is used. Even though this component updates the application's state, I believe that because it has no internal state, it is not necessarily behavioral.
Again, I don't think there is really a right or wrong way of doing things here. It reminds me of the discussion about whether or not Redux should handle all application state. I think if you keep the idea of making presentational components as dumb (reusable) as possible, you can figure out the correct place to put lifecycle methods in any case.
Your question is not very correct.
Simple act of using a lifecycle method doesn't define the component as a presentational or a container component.
Lifecycle methods are exactly that — the hooks for your convenience where you can do pretty much anything you want.
A container component typically does some setup that connects itself to your application's data flow in those lifecycle methods. That's what makes it a container component, not the bare fact that it uses some lifecycle methods.
Presentational components are typically dumb and stateless, therefore they typically don't need those lifecycle methods hooked into. This doesn't mean that it's always the case. A presentational component may be stateful (although this is often undesired) and a stateless component may make use of the lifecycle methods, but in a totally different fashion than a container component would. It might add some event listeners to the document or adjust the cursor position of an input in a totally stateless way.
And perhaps you're mixing up container components and stateful components. Those are different things, and while container components are stateful, stateful components don't necessarily acts as container components.

Resources