Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Intro
Concepts below were aggregated in Suicrux.This guide on Github.
In this series of articles we will try to abstract from certain libraries and take a wider look at more fundamental things.
Part 1:
- Folders structure
- Components structure and hierarchy
- âStyled componentsâ approach
- Important fundamental concepts (selectors and initial states)
What to use for âŠ
Almost every library has a âcloneâ (alternative). You can find more than one library to solve a specific task. That means when you see a reference to React Router be sure that there is a âcloneâ of this library, but for Preact.
Component-based library
You can use React/Preact/Inferno. It doesnât really matter. React is well-known and canonical. Preact is small and could be used only for production. Inferno seems to be faster than any other lib according to some benchmarks.
But this âspeedâ doesnât matter in âreal-lifeâ. 90% of speed issues caused by bad optimization of your app, not a framework. So there is no difference what library to choose(except size).
Must-have libraries:
- `react-router`(or another routing library),
- `react-helmet`(easily manipulate <head>Â tag).
Flux-architecture library
Mobx/Saga/Redux/Flux/Keaâââit doesnât really matter.
When you use any of these librariesâââyou use the same flux-architecture concept.
- `redux-thunk`, `react-redux`, etc.âââobviously.
- `react-router-redux`âââsync your library with location. (Also, RRRv5 sometimes doesnât work as you expect).
- `promise-middleware`âââsmart solution to use promises as an action payload and evaluate them using middleware. (will cover in next article)
Styles & Styled components
âStyled componentsââââdesign approach. âThinking in components, styling in componentsâ.`Styled-components`âââlibrary to design styled components in React using HOCs.
- `styled-components`âââbloated, requires good understanding of CSS methodologies. But itâs very powerful and has a rich API.
- `glamorous`âââAPI similar to `styled-components`, lightweight, good performance.
- `emotion`âââAPI similar to `styled-components`, has âextract modeâ that makes it fast.
- `glamor`âââlightweight and simple inline-css library. `glamorous` is based on `glamor`.
Whatâs a problem with âstyled componentsâ?
- Sometimes hard to overwrite a CSS framework.
- There is no styling methodology, and SMACSS/BEM/etc. will not work well.
- Sometimes you could incorrectly connect your app logic with styles.
You have to design your own styling strategy to write configurable, fast, composable components. Personally, I didnât find any new methodology for styled components, but can give you some recommendations:
- Donât pass too many different props.
- Donât make a styled component for every custom component in your app.
- HOCs could save you a lot of time.
- Donât mix logic props and UI props (font size, color)
Remember that all these libraries were created to solve same issues.
UI
Probably, this article with a comparison of different UI frameworks could help you select a framework for the next project.
If you want fast UI framework then select a framework powered by library like `styled-components` or inline-css lib.
Donât know current MUI development progress, but as of July-Aug 2017:- it was(!) slow, but according to the latest news right now perf is better.- design isnât 100% material.Semantic-UI-Reactâââmany components out-of-box, but requires full Semantic CSS file. (548 kb ungzipped).âAnt designâ looks great.
Webpack
As of 2017, your project must be universal. Itâs very important. Both server and client must have hot-reloading.
Step-by-step guide how to achieve universality. Also, itâs an alternative to most solutions. One port and FS instead of 2 ports and different FSs.
- Compile both server and client with Webpack
- Extract shared config for both server and client (e.g. loaders, plugins for both server and client)
- Extract your production and development configs in a separate module and save it for the next project.
Frameworks(Next.js) and starters (razzle) supports custom Webpack configs (the end of old-fashioned starters era is soon). Keep in mind, some project supports custom Webpack config only partly. Thatâs the only reason why starters are still used.
Some plugins you could have missed:
- `circular-dependency-plugin`âââdetects circular dependencies
- `autodll-webpack-plugin`ââârecompile only updated code, without vendor bundle
- `write-file-webpack-plugin`âââwrite files from memory FS to real FS. (e.g. write files from webpack-dev-middleware to FS)
- `assets-webpack-plugin`âââget webpack stats (similar to `webpack-stats-plugin`, but better)
Static-typing
Flow.
TypeScript is great and has more features than Flow. But keep in mind that when you use TypeScriptâââyou dive into the TypeScript world. That means you use âanotherâ language with own ecosystem.
When you use Flow you just create an abstraction around your dynamic-typed code and still write JavaScript.
ESlint
Standard code style is â€ïž.If you care about a11y (accessibility)âââadd eslint-plugin-jsx-a11y.
Itâd be better to use eslint-plugin-standard than standard package, some default Standard rules are annoying, like no-tabs, no-unused-vars and indent.
Babel
Add babel-preset-react-optimize in production.Donât forget to add styled-components plugin, if you use styled-components library. Also, module-resolver plugin is very useful.
Folder structure
There are many approaches to structuring react/redux project. Keep in mind, that this structure may vary according to your framework, setup, etc. For example, Next.js, CRA already have some predefined folders.âââ âŠâââ jest_config # Test configuration lives here. jest in this case.âââ src | âââ client # Entry file for browserâ âââ common # Sources for both browser and serverâ âââ server # Server codeâââ webpack_configâ âââ client # Webpack config for clientâ âââ server # Webpack config for serverâââ âŠ
Probably, jest_config and webpack_config dirs are obvious. So letâs take a look at the /src folder.
`/src/client`
This is your browser entryâââcode that renders an app in a browser, imports framework styles, polyfills, your global styles, PWA setup. It could be in /common folder too, but putting it into distinct folder seems more semantically correct.
`/src/server`
Your server-side code.
`/src/common`
Thatâs the place where the most interesting things happen. /commonâââ actions # Actions âââ api # API (requests, data management utils)âââ app # App core(boot loader)âââ components # Reusable componentsâââ constants # Constant values, like months names, etc.âââ containers # App routesâââ pwa # Progressive Web App code (optional)âââ reducers âââ selectors âââ styles # Styled components + global CSSâââ types # Flow types for your appâs entities
Routes (`/containers`)
Almost every route has own /components folder where specific for this route components are stored, i.e.:
- container = containers/App/index.jsx
- routeâs component = containers/App/components/SomeAppItem.jsx
Components
Component vs PureComponent vs âstateless componentâDifferences between components types.
Keep in mind, that change of component type doesnât guarantee performance improve.
Containers vs Components
Follow Dan Abramov âs guide:
- ContainerââââsmartâReact component connected to Redux state.
- Componentââââdumbâ React component that uses only own props. Canât be connected to Redux.
There are no practical recommendations about structuring /components folder, except âatomicâ approaches and other heuristics (those have never worked for me). Semantic UI glossary proposes similar to âAtomicâ approach that works better than analogs (but still isnât perfect).
Glossary Of Terms | Semantic UI
A component is a general term used to refer to any user interface element packaged for distribution.Parts
There are always components that exist in one instance, like Sidebar, Header, Footer, etc. Store singletons in /parts dir.
SUI doesnât propose âpartsâ.ViewsA view is a common design trope for presenting specific types of website content like comments, or user activity. These are common views: comments, activity feeds, content cards, that are presented in a similar fashion across most websites.
If a component is a parent for other components, represent some content, and itâs dumb then itâs probably a âviewâ.
Addons
Component may be an âaddonâ, if this component is a wrapper for another component, or a component that could be perfectly replaced by a library, but was developed from scratch (custom spinners, progress bars).
Component is an âaddonâ, ifâŠ
- itâs a wrapper for another component
- it is small lib implemented inside the project
ElementsUI elements are the smallest atomic unit for describing page content. They can exist alone or in groups with shared qualities.
Component is an âelementâ, ifâŠ:
- small +Â dumb
- widely used in other components
- built from scratch
CollectionsCollections are heterogeneous group of several ui elements which are usually found together. They may describe ui elements which do not necessarily have to be present.
âCollectionâ differs from âviewâ:
- âviewâââârepresents specific for sites content.
- âcollectionââââdoesnât represent specific content. Grouped different components.
ModulesModules are UI components that have behaviors as an essential part of their definition. These include things like, accordions, dropdowns, and popups, which require not only a description of how they appear, but also a set of instructions for how to implement their behaviors.
When your component has some logic inside (e.g. `onClick` handler), this component is a module. Module is a component logically connected to a parent component.
BehaviorsBehaviors are instructions for UI behavior that are not attached to a particular physical form. They may describe things like, form validation, state management, or server request routing.
Component that doesnât exist as UI element, but brings some logic. Like components those implement animations. Example: react-motion and react-fns
PWA
Use Offline-Plugin. It requires zero config as long as you:
- Donât have SSR (sometimes).
- Donât have auth logic that relies on location. (e.g. redirect to /auth, if user isnât logged in)
- Donât have other specific logic that relies on location.
- Donât have specific requirements to caching, cache validation or anything similar that connected to offline.
If you got one of these featuresâââitâd be better to test your PWA setup in different browsers with different behaviors/app flows.
Reducers
Dissecting Twitterâs Redux Store. You can make your own research and dissect any popular app. Pinterest, for example.
95% of all states in any app can be interpreted as:
The main key to Redux development:
Your state is just an in-memory DB.Donât store things those could be computed by selectors.
Selectors
Always use selectors, itâs very important!
What is a âselectorâ? If your mapStateToProps looks like:
Then youâre doing that wrong, because:
- every time the way you compute some value changes, you have to change it across a whole app.
- every time your state structure changes, you have to fix path to the property across a whole app.
- you connect your computational(selectional) logic with your container, container shouldnât know about it.
Instead:
Routing, Async actions, API
In the next article, we willâŠ
- build complex routing with auth protection
- review all approaches to async actions and data management in Redux
- play with redux-form and other libs
Thanks for reading!Github: @MetnewTwitter: @vladimir_metnew
Strategical view on component-based libraries with flux-architecture paradigm. Part 1. was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.