Search code examples
javascriptreactjsfunctionhigher-order-components

When to use HOC. When to use Function as child


I am quite confused. I learned not so long ago about HOCs. Even though I wasn't able to make a really good (useful) HOC yet, I understand how it's working. (Well if someone could give me some real world solutions with HOC I would thanks it :D). But then... there is the thing I just read NOW: function as child

return (
    <div>
        {this.props.children(this.state.visible)}
    </div>
)


{(visible) =>
    visible ?
    <Placeholder/> : ''
}

It's looks REAAALLY cool but just as with HOC, I am not sure where could I use it, AND where can I use it instead of HOC (and vice versa).

(In reality I am more confused with the Function as Child (know how its work). I got no idea where should I use it, and why over HOC).


Solution

  • I use HOC for PrivateRouting. Here is one example when checking if user is authenticated with redux.

    import React from 'react';
    import { connect } from 'react-redux';
    import { Route, Redirect } from 'react-router-dom';
    import Header from '../components/Header';
    
    export const PrivateRoute = ({
      isAuthenticated,
      component: Component,
      ...rest
      }) => (
        <Route {...rest} component={(props) => (
          isAuthenticated
            ? (
              <div>
                <Header />
                <Component {...props} />
              </div>)
            : (<Redirect to="/" />)
        )} />
      );
    
    const mapStateToProps = (state) => ({
      isAuthenticated: !!state.auth.uid
    });
    
    export default connect(mapStateToProps)(PrivateRoute); 
    

    // USAGE

    <PrivateRoute path="/edit/:id" component={SomeEditPage} />
    

    If user is authenticated then he can go and edit something, if not it will route him to home Route ('/')