I'm wondering if there's a pattern that allows me to prevent an HOC from recalculating based on some condition, here's an example:
const DumbComponent = () => <button>Click me<button/>;
// Third party HOC, that I can't modify
const SmartComponent = Component => class extends Component {
componentWillReceiveProps() {
// Complex stuff that only depends on one or 2 props
this.state.math = doExpensiveMath(props);
}
render() {
return <Component {...this.props} math={this.state.math} />;
}
}
const FinalComponent = SmartComponent(DumbComponent);
What I'm looking for, is a pattern that prevents this HOC from doing its thing if the props I know it depends on haven't changed. But that doesn't stop the entire tree from rerendering based on props like shouldComponentUpdate would do.
The catch is, that this HOC comes from another library and ideally I don't want to fork it.
What i got is you want to prevent hoc to recompute certain logic for that you can do as below :-
const DumbComponent = () => <button>Click me<button/>;
// Third party HOC
const SmartComponent = Component => class extends Component {
componentWillReceiveProps() {
// Complex stuff that only depends on one or 2 props
this.state.math = doExpensiveMath(props);
}
render() {
return <Component {...this.props} math={this.state.math} />;
}
}
const withHoc = SmartComponent(DumbComponent);
class FinalComponent extends Component {
render() {
if (your condition here) {
return (
<withHoc {...this.props} />
);
}
else {
return <DumbComponent {...this.props}/>;
}
}
}
export default FinalComponent;
Related
I have a component which is going through an hoc, but i want to get some props of this component inside the hoc. All works fine but i can not find out how to get the props out of this child component into the hoc.
here is the component which is going through the hoc, and that is this 'getAction' props i want to extract in the hoc
class ProjectPage2 extends Component {
render() {
return (
<Project2 getAction="getAction"/>
);
};
};
export default PageHandler(ProjectPage2)
here is the hoc component (imported as PageHandler in the ProjectPage2)
export default (ChildComponent) => {
class ComposedComponent extends Component {
render() {
// here i want to get the 'getAction' props, which is inside this ChildComponent
// because i need to use it into this hoc logic
return <ChildComponent {...this.props} />;
}
}
const mapStateToProps = (state) => {
return {
comments: state.project2
}
};
const loadData = (store) => {
return store.dispatch(getProject2());
};
return {
loadData,
component: connect(mapStateToProps, { getProject2 })(ComposedComponent)
}
};
if some one have an idea it would be great. Thanks.
I think you're very close already. It looks to me like you want the final result to be something like:
<Project2 getAction="getAction" comments={...} />
But what ends up getting rendered is just:
<Project2 getAction="getAction" />
See, the custom props of your HOC are passed to your child component via the child's props. You aren't using those, so the child just completely ignores the HOC. You can fix this with:
class ProjectPage2 extends Component {
render() {
return (
<Project2 getAction="getAction" {...this.props} />
);
};
}
Thank you for the answer. But it s not what i was looking for. I wanted to get into the HOC some children component's props passing through. But i finally get the idea which solved it. In fact it s so simple......
i wanted to pass the "getAction" string into the HOC. But i didn t find any solution to extract it (from the passing through component) there.
The solution is simply to pass it into the export default
class ProjectPage2 extends Component {
render() {
return (
// i was trying to use the component props
// <Project2 getAction="getAction"/>
// but no need
<Project2 />
);
};
};
// pass it into the fonction fix it
export default PageHandler(ProjectPage2, "getAction")
then get it in the HOC
export default (ChildComponent, varAction) => {
class ComposedComponent extends Component {
console.log(varAction) // return getAction
I'm building a Web components library where I have a series of components which ideally inherit / takes advantage of BaseComponent. After some reading, inheritance isn't recommended in React and instead I could use forwardRef? or probably higher-order components? The only thing, I'm not very familiar with this concept and couldn't find good examples, tutorial specific for my case. Hopefully someone can tell me how to approach this, what's best-practice?
One of technique I have in mind for the BaseComponent is leveraging IntersectionObserver to trigger animations. As you can imagine, I don't want to put this logic in multiple places. For the sick of having a basic example, below I simply have a click event listener on the BaseComponent:
class Image extends React.Component {
render() {
return (
<div>
<div>
<img className={className} src={src} alt={alt} />
</div>
</div>
);
}
}
export default Image;
// export default withMagic(Image); ??
class BaseComponent extends React.Component {
withMagic() {
}
componentDidMount() {
{/* ref should be <img> DOM element */}
ref.addEventListener("click", this.handleClick);
}
}
export BaseComponent();
Thanks
HoC probably the better solution
// 2. WrappedComponent
export default WrappedComponent => {
// If u want to deal with class
class NewComponent extends React.Component {
//3
handleClick = () => {
// Your Events
}
render () {
//4
return <WrappedComponent {...this.props} handleClick={this.handleClick} />
}
}
// If u want to deal with functional Component
const NewComponent = props => {
const handleClick = () => // your events
return <WrappedComponent {...props} handleClick={handleClick} />
}
return NewComponent
}
How to use ?
import withClick from 'path/withClick'
const A = props => {
return (
//4
<button onClick={props.handleClick}>Click here</button>
)
}
// 1.
export default withClick(A)
How this magic work ?
U are using withClick method by passing A component as a params
A component is named as WrappedComponent inside withClick function
inside the withClick function, u create a new component with your desired handler, logic or even state, then pass them as a props into WrappedComponent
after that, ur current component will have these handler or logic
If u want to pass params, u can use Higher order Function that returns Higher Order Component like
export default (params1, params2, ...paramsn) => WrappedComponent => {
// remain like the same
}
I'm trying to apply the HOC to every child in my custom component. But I can't solve how to implement this for dynamic wrapped component type. Let say we have:
function myHOC<P>(WrappedComponent: React.ComponentType<P>):React.ComponentType<P> {
return class extends React.Component<P> {
...
render() {
return <WrappedComponent />;
}
const MyHOC = myHOC(???); //It won't do!
class MyComponent extends React.Component<Props, State> {
...
render() {
const items = this.props.children.map((child) => {
<MyHOC /> //I want to use it something like this!
});
return (
<div>
{items}
</div>
);
}
}
What do I need to add?
You can't apply HOC dynamically. If you want to use shared stateful logic dynamically you can think about render props pattern.
I wondering if it would be possible to use React 16's lazy, Suspense, createRef and forwardRef features together in order to attach a reference to a dynamically imported component. Does anyone know if this is possible. I tried to follow the example (https://github.com/facebook/react/pull/13446/commits/4295ad8e216e0747a22eac3eed73c66b153270d4#diff-e7eafbb41b012aba463f5a2f8fc00f65R1614), however it doesn't quite seem to work with dynamically imported components.
I have been able to get similar desired behavior by setting custom props in the parent component, passing it down to the child component and then setting the ref to that prop in the child's render function(Example below). My only issue with this approach is that it may not be the cleanest solution and it may be difficult to keep the implementation consistent across a large team. It will also make it easier when attempting to place the ref on the actual component.
// Working (Undesired implementation)
// Parent.js
const LazyClass = lazy(() => { return import('./Child') };
class Parent extends React.Component {
this.childRef = React.createRef();
render() {
return (
<Suspense fallback={<div>Loading</div>}>
<Child forwardRef={this.childRef} />
</Suspense>
);
}
}
// Child.js
class Child extends React.Component {
render() {
return (<div>I am the Child!</div>);
}
}
export default React.forwardRef(({forwardRef, ...props}/*, ref*/) =>
<Child {...props} ref={forwardRef} />
);
//////////////////////////////////////////////////////
// Desired Implementation with React.forwardRef()
//Parent.js
const LazyClass = lazy(() => { return import('./Child') };
class Parent extends React.Component {
this.childRef = React.createRef();
render() {
return (
<Suspense fallback={<div>Loading</div>}>
<Child ref={this.childRef} />
</Suspense>
);
}
}
// Child.js
class Child extends React.Component {
render() {
return (<div>I am the child</div>);
}
}
export default React.forwardRef((props, ref) =>
<Child { ...props } ref={ref} />
);
Setting the ref directly on a Lazily loaded component always returns null. It would be nice if it returned the value from React.createRef().
The "ref as a props" approach is the smaller one but as you said you have to consider prop collision. The approach you linked is still correct. The test only changed slightly:
Update: Not sure if this was a bug previously but lazy now forwards refs automatically. Just be sure you export a component that can hold a ref.
See in action:
https://codesandbox.io/s/v8wmpvqnk0
I am running a pattern like so, the assumption is that SearchResultsContainer is mounted and somewhere a searchbar sets the input.
class SearchResults {
render() {
return(
<ResultsContext.Consumer value={input}>
{input => <SearchResultsContainer input=input}
</ResultsContext.Consumer>
)
}
class SearchResultsContainer
componentDidUpdate() {
//fetch data based on new input
if (check if data is the same) {
this.setState({
data: fetchedData
})
}
}
}
this will invoke a double fetch whenever a new context value has been called, because componentDidUpdate() will fire and set the data. On a new input from the results context, it will invoke componentDidUpdate(), fetch, set data, then invoke componentDidUpdate(), and fetch, then will check if data is the same and stop the loop.
Is this the right way to be using context?
The solution I used is to transfer the context to the props through a High Order Component.
I have used this very usefull github answer https://github.com/facebook/react/issues/12397#issuecomment-374004053
The result looks Like this :
my-context.js :
import React from "react";
export const MyContext = React.createContext({ foo: 'bar' });
export const withMyContext = Element => {
return React.forwardRef((props, ref) => {
return (
<MyContext.Consumer>
{context => <Element myContext={context} {...props} ref={ref} />}
</MyContext.Consumer>
);
});
};
An other component that consumes the context :
import { withMyContext } from "./path/to/my-context";
class MyComponent extends Component {
componentDidUpdate(prevProps) {
const {myContext} = this.props
if(myContext.foo !== prevProps.myContext.foo){
this.doSomething()
}
}
}
export default withMyContext(MyComponent);
There must be a context producer somewhere :
<MyContext.Provider value={{ foo: this.state.foo }}>
<MyComponent />
</MyContext.Provider>
Here is a way to do it that doesn't require passing the context through props from a parent.
// Context.js
import { createContext } from 'react'
export const Context = createContext({ example: 'context data' })
// This helps keep track of the previous context state
export class OldContext {
constructor(context) {
this.currentContext = context
this.value = {...context}
}
update() {
this.value = {...this.currentContext}
}
isOutdated() {
return JSON.stringify(this.value) !== JSON.stringify(this.currentContext)
}
}
// ContextProvider.js
import React, { Component } from 'react'
import { Context } from './Context.js'
import { MyComponent } from './MyComponent.js'
export class ContextProvider extends Component {
render(){
return (
<MyContext.provider>
{/* No need to pass context into props */}
<MyComponent />
</MyContext.provider>
)
}
}
// MyComponent.js
import React, { Component } from 'react'
import { Context, OldContext } from './Context.js'
export class MyComponent extends Component {
static contextType = Context
componentDidMount() {
this.oldContext = new OldContext(this.context)
}
componentDidUpdate() {
// Do all checks before updating the oldContext value
if (this.context.example !== this.oldContext.value.example) {
console.log('"example" in context has changed!')
}
// Update the oldContext value if the context values have changed
if (this.oldContext.isOutdated()) {
this.oldContext.update()
}
}
render(){
return <p>{this.props.context.example}</p>
}
}
You could pass just the value that is changing separately as a prop.
<MyContext.Provider value={{ foo: this.state.foo }}>
<MyComponent propToWatch={this.state.bar}/>
</MyContext.Provider>
The extent -> props wrapper seems to a recommended by the react staff. However, they dont seem to address if its an issue to wrap context in a prop for an then consume the context directly from the child of the child, etc.
If you have many of these props you are needing to watch, especially when not just at the ends of branches for the component tree, look at Redux, its more powerful that the built in React.extent.