Felipe Deitos
Felipe Deitos

Reputation: 194

React Hook Pattern Tips

I'v used to build applications using react + mobx, doing stores and passing them down trought a provider and injecting with decorators. (Some of those applications are bigs, lots of data, forms, grids...)

// store.js
class Store {
    @mobx.observable counter = 0;

    @mobx.action
    increaseCounter = () => {
        this.counter++;
    }
}

// App.js
class App extends Component {
    constructor(props){
        super(props);
        this.store = new Store();
    }
    
    render(){
        return(
            <mobx.provider store={this.store}>
                <AppChildren />
            </mobx.provider>
        );
    }
}

// AppChildren.js
@mobx.inject('store')
class AppChildren extends Component {
    render(){
        const { counter, increaseCounter } = this.props.store;

        return(
            <div onClick={increaseCounter}>{counter}</div>
        );
    }
}

In this examples no matter how many childrens in the tree I have, I'll always be able to inject the store and work with it WITHOUT passing the state/observables trought props down, and again, and again, and again (This application its a little bit old, I know context its better now).

I'm trying to keep up with react methodologies, so I'v read about the hooks, and already played a little with it, there are some pattern similar to this one presented above? Theres something better than that?

Well if someone have a tip, an article, tutorial or anything I'll really apreciate!!

Upvotes: 1

Views: 638

Answers (1)

Danila
Danila

Reputation: 18516

For functional components you can use this hook:

import { MobXProviderContext } from 'mobx-react'

function useStores() {
  return React.useContext(MobXProviderContext)
}


// usage

function Component() {
  const { userStore, someOtherStore} = useStores();

  return (...)
}

You still need to pass your stores to mobx Provider.

More info about this and other approaches there https://mobx-react.js.org/recipes-context

Upvotes: 1

Related Questions