ReactJs: Using stores to improve your code

Image credits: https://seriousseverity.wordpress.com

I’m a sucker for well written code. When code is badly written, the app kinda gets boring and it becomes a task to work on the codebase. I love stores in js, especially since es6. Simple classes with very profound effects on how you work. I’d like to share one or two things on how I make use of them in my work.


Images

One of the first steps i take is to create an ImageStore. This helps me keep all images in one place, helps ensure my images are compiled with react and also helps me not worry about relative links to my app root.

So some code:

//say the name of this file is ImageStore located at stores/ImageStore
import UserImage from ‘../assets/img/image1.svg’
import FriendImage from ‘../assets/img/image2.svg’
export default {
UserImage,
FriendImage
}

Then to import it in your views

import ImageStore from './stores/ImageStore
// excluded some imports for brevity sake
...
...
...
export default class TestClass extends Component {
render()
<img src={ImageStore.UserImage} alt='User' />
...
...
   }
}

Thats it. Just add all images you wish to use in your app into the store and import the ImageStore. No relative links required, the image gets compiled into your app and best of all, if the image location needs to change for any reason all you need to do is change in the ImageStore file and it changes everywhere.


Stores

I handle my stores in a very similar manner to how I handle Images, the only difference is how my stores are exported. Again, the advantage of this method is that you don’t have to worry about relative links, your code is cleaner and if the location ever changes you just need change it in one place and it takes effect all through your app

//Say the name of the Store that manages Stores is StoreManager 
import AuthStore from './stores/AuthStore’;

import PostStore from './shared/stores/PostStore’;
...
...
export {
AuthStore,
PostStore
}

Then import in your app this way:

import {AuthStore, PostStore} from './stores/StoreManager'
...
...
...
export default class TestStoreManager extends Component {
 componentWillMount () {
PostStore.someFunc()
...
 }
}

There, its that simple. No messy code.


You can basically put anything in a store. My rule of thumb is anything has a relative link or that I will need repeatedly across my app goes in a store. Other things you could put in a store are your constant string values etc. Find out how best stores suit you and make use of it.

Note: This method works for angular2 as well. Its no a react thing, but i just used it here in relation to react. All you need do is create a .ts file and export. You can do this for all your declarations array, imports array etc.