Techniques for decomposing React components – DailyJS – Medium

Techniques for decomposing #ReactJS components:  by @Dvtng #JavaScript

  • Here are three techniques to get you started, from the simplest to most advanced.Split the render() methodThis is the most obvious technique to apply: when a component renders too many elements, splitting those elements into logical sub-components is an easy way to simplify.A common and quick way to split the render() method is to create additional “sub-render” methods on the same class:While this can have its place, it is not a true decomposition of the component itself.
  • As a bonus, when React’s new Fiber architecture arrives, the smaller units will allow it to perform incremental rendering more effectively.Templatize components by passing React elements as propsIf a component is becoming too complex due to multiple variations or configurations, consider turning the component into a simple “template” component with one or more open “slots”.
  • Utilise the ability of React to pass elements, not just data, as props, to create a flexible template component.Another component can then have the sole responsibility of figuring out what to fill the metadata and actions slots with.Keep in mind that in JSX, anything that’s between the opening and closing tags of a component is passed as the special children prop.
  • In the comments example, this would likely be the text of the comment itself.Extract common aspects into higher-order componentsComponents can often become polluted by cross-cutting concerns that aren’t directly related to its main purpose.Suppose you wanted to send analytics data whenever a link in a Document component is clicked.
  • The obvious solution might be to add code to Document’s componentDidMount and componentWillUnmount lifecycle methods, like so:There are a few problems with this:The component now has an extra concern that obscures its main purpose: displaying a document.If the component has additional logic in those lifecycle methods, the analytics code also becomes obscured.The analytics code is not reusable.Refactoring the component is made harder, as you’d have to work around the analytics code.Decomposition of aspects such as this one can be done using higher-order components (HOCs).

React components have a lot of power and flexibility. With so many tools at your disposal, it is incredibly easy for components to grow over time, become bloated and do too much. As with any other…
Continue reading “Techniques for decomposing React components – DailyJS – Medium”

“Using Functions as Children and Render Props in React Components” #reactjs #javascript

“Using Functions as Children and Render Props in React Components”  #reactjs #javascript

  • Here we are using the component, passing in a function, and then returning some content.
  • The component is able to manage all the state without leaking it’s logic into any other component.
  • This type of component is applicable for times when you need to reload the specific data each time.
  • Additionally if there is additional logic like sticky headers, the outer component doesn’t need to know anything about the logic required to do so.
  • With children as functions we are still able to compose our components like any other React component.

React allows for you to specify a function as a child, which children is just a normal prop so it is equivalent to a render callback.
Continue reading ““Using Functions as Children and Render Props in React Components” #reactjs #javascript”

Using RxJS with React.js: Part 3 — Dispatching events from Component

Using RxJS with React.js: Part 3 - Dispatching events from Component

  • Using RxJS with React.js: Part 3 — Dispatching events from ComponentThis is the third part of the series.Illustration of unidirectional flow between Subject and ComponentUnidirectional cycleEarlier we saw an example of HoC streaming props to the base component.
  • Let’s now look at ways how we can dispatch events from inside the base component, update some value, and the updated value will then be streamed back to the component completing one unidirectional cycle.We can take the example of a form input field.
  • To keep things simple, let’s say BehaviorSubject is a kind of Subject, that can already start with an initial value.import { BehaviorSubject } from ‘rxjs’;const subject$ = new = console.log(x)); // prints `foo` right awayThe base Component with form inputLet’s say this is our base component:import React from ‘react’const MyComponent = React.createClass({ render() { const { value, handleChange } = this.props; return ( div input type=”text” value={value} onChange={e = handleChange(} / pCurrent value: {value}/p /div ); }});From the base component, we are accessing the props value and handleChange.
  • First one is a stream of the input value, and the latter for handling the change.import { BehaviorSubject, Observable } from ‘rxjs’;const formInput$ = new BehaviorSubject(‘foo’); // with initial valueconst handlers$ = Observable.of({ handleChange: value = formInput$.
  • scan(function (props, emitted) { return { …props, …emitted }; });Observing the base ComponentNow that we have the props$ observable ready, we can integrate it with our base complement easily using the observe function from FrintJS:import { observe } from ‘frint-react’;const ObservedRoot = observe(function () { return props$;})(MyComponent);Now you can stream the props, including both the input value and the change handler from your HoC, and also trigger changes in the Subject from your Component’s events.Live demoVisit this example in JSBin.

Earlier we saw an example of HoC streaming props to the base component. Let’s now look at ways how we can dispatch events from inside the base component, update some value, and the updated value will…
Continue reading “Using RxJS with React.js: Part 3 — Dispatching events from Component”

Inspired by the #ReactJS version of Tetris, this amazing adaption is made with Vue #NodeJS

Inspired by the #ReactJS version of Tetris, this amazing adaption is made with Vue


  • English introduction
    Please view React 版的俄罗斯方块,由于对其实现原理较感兴趣,而且相比于 React 更喜欢 Vue, 于是把 React 版的重构为了 Vue Redux 使用 Vuex Vue + Vuex,其中再加入了 Immutable.js,确保性能和数据可靠性
    1、什么是 Immutable?
    Immutable 是一旦创建,就不能再被更改的数据。对 Immutable 对象的任何修改或添加删除操作都会返回一个新的 Immutable 对象。
    function keyLog(touchFn) {
    let data = { key: ‘value’ };
    console.log(data.key); // 猜猜会打印什么?
    不查看f,不知道它对 data 做了什么,无法确认会打印什么。但如果 data 是 Immutable,你可以确定打印的是 value:
    function keyLog(touchFn) {
    let data = Immutable.Map({ key: ‘value’ });
    console.log(data.get(‘key’)); // value
    JavaScript = {a: 1}; bar = foo; bar.a = 2;
    foo.a // = Immutable.Map({ a: 1 }); bar = foo.set(‘a’, 2);
    foo.get(‘a’) // 1
    关于 b:2, c:3} === {a:1, b:2, c:3}; // false
    [1, 2, [3, 4]] === [1, 2, [3, 4]]; // false
    对于上面只能采用 = Immutable.Map({a:1, b:2, c:3});
    map2 = Immutable.Map({a:1, b:2, c:3});, map2); // true

    // List1 = Immutable.List([1, 2, Immutable.List[3, 4]]);
    List1 = Immutable.fromJS([1, 2, [3, 4]]);
    List2 = Immutable.fromJS([1, 2, [3, 4]]);, List2); // true

    2、Web Audio Audio Audio Api ;
    左右移动可以 delay 掉落的速度,但在撞墙移动的时候 delay 的稍小;在速度为6级时 通过delay 模拟 visibilitychange Vuex ios React 项目重构为 Vue 版本
    Vue 版本和 React 版的 store 使用了 immutable 结构的数据,vuex 上的 store 如果使用了 immutable 结构,不利用监听数据变化,故把store 的数据全部使用了普通的数据,在需要这些数据的地方通过 immutable 提供的 fromJS 转换,在需要普通数据的地方再通过 immutable 的 toJS React 组件改写成 Vue React 的 setState 会触发 render 方法,所以可以在 methods 自定义 render 方法再在 state 变化后手动触发 render 方法

    生命周期,简单来说, React 的 componentWillMount 对应 Vue 的 beforeMount, React 的 componentDidMount 对应 Vue 的 mounted,React 的用来优化性能的 shouldComponentUpdate 在 Vue 里并不需要,不需要手动优化这也是我喜欢 Vue 的一点

    Vue 没有 React 的componentWillReceiveProps 的生命周期,我的解决方法是使用 watch 配合 deep:true 来监听 props 的变化,如:

    watch: {
    $props: {
    deep: true,
    handler(nextProps) {

    在必要时候使用 jsx 和 ‘render’ 函数,是的, vue 支持 jsx,在这个项目中matrix 组件 的功能逻辑较复杂,使用 template 模版来渲染组件已经不合适了, React 每次 setState 会触发 ‘render’ 方法,所以我们可以在 methods自定义 ‘render’ 方法再在 state 变化后手动触发 ‘render’ Vue 的 jsx jsx 语法对页面进行渲染,当 props 或 state 变化了自动触发 ‘render’ 方法,另外要注意的是 vue 的 jsx 和 React 的 jsx 书写上有一点的差异, 当 ‘render’ 方法存在时,template 语法会失效.

  • ‘render’ 函数一个比较实用的用处是在开发类似 React-log 之类的不需要渲染 html 只需要执行一些方法的组件时 template 会显得很多余,因为这时候并不需要渲染 dom 了,如果用了 ‘render’ 函数,简单的在 ‘render’ 函数里 return false 就行,如: react-log

    Redux 的数据流向是通过 mapStateToProps 把 store 的状态转化为 props 然后通过connect 函数注入到 根组件,根组件再把这些 props 传入不同组件,当 store 的状态变化,根组件会重新 render, 更新子组件上的 props,子组件再 根据新 props重新 vuex 的思路则不同,任何组件都随时可以通过 this.

  • $ 获取 store 上的数据,更自由,从 store {
    keyboard () {
    调用 store.commit 提交 payload修改数据 或者 store.dispatch 提交 mutation 间接修改 store 上的数据, commit 和 dispatch 的区别在于 commit 用于同步修改状态, dispatch 用于异步修改状态,异步完成需要再调用 commit,一般简单的需求只需要 commit 一个 payload 就行,只要 store 上的数据变了,组件都会自动重新渲染
    npm install

    npm run dev

    浏览自动打开 http://localhost:8080
    在 i18n.json run build

    在 dist 文件夹下生成结果。

vue-tetris – Use Vue, Vuex, Immutable to code Tetris.
Continue reading “Inspired by the #ReactJS version of Tetris, this amazing adaption is made with Vue


Topcoder Getting Started with ReactJS

Getting Started with ReactJS - A blog that is supplemented by a Fun Challenge!

  • ReactJS uses JSX to transpire the HTML element on the web page.
  • React first converts JSX into a JavaScript file that is rendered by the browser, resulting in HTML code.
  • BABEL converts JSX code in JavaScript and takes care of cross-browser compatibility.
  • ReactJS functions are called components.
  • ReactJS gives us power to pass data between components and we do it using props and states.

Have you ever thought of passing your HTML code into JavaScript code? How about displaying HTML elements via JavaScript?
Continue reading “Topcoder Getting Started with ReactJS”

Optimizing React Rendering (Part 1) – Flexport Engineering

Optimizing React Rendering (Part 1)  #Reactjs #Javascript #Webdev

  • PureComponent does a shallow object comparison on the props, and since you are passing in the same object reference, shouldComponentUpdate will return false and the updated data will not be rendered.This means that if any part of your app mutates data that needs to be rendered, PureComponent puts you at risk of displaying stale data.
  • This is by far the biggest blocker because it results in incorrect UI behavior, and it is outside the control of your component.Fix: Never mutate values used as React props or state.
  • Even if some ancestor component triggers a re-render, PureParent will not re-render because neither its state or props has changed.This gotcha also leads to incorrect UI behavior, but the issue is scoped to the component itself, making it easy to fix.Fix: Extract data dependency into state or props, and update state or props when the data changes.Object copyingQ: What happens when Parent is re-rendered with an unchanged props.dataList?A: PureChild is re-rendered wastefully because filter returns a new object, which tricks PureChild into thinking that the prop has changed.This problem is triggered by calling any function that creates a new object or using an inline object literal in render.Fix: Cache your derived data calculations.
  • A: PureChild is re-rendered wastefully because arrow functions and Function.prototype.bind return new function instances, which tricks PureChild into thinking that the onClick handler has changed.Fix: Don’t use arrow functions and bind in render.
  • When those props change, PureChild will re-render wastefully.Fix: Unless you’re writing some sort of higher-order-component, don’t be lazy and be explicit about the props that you are passing.ConclusionTurns out our app is littered with every single one of these gotchas, and is especially dependent on mutation side-effects.

We migrated our web app to React almost 3 years ago, and since React performs extremely well out of the box, optimizing performance was not something we had to worry about. However, as our…
Continue reading “Optimizing React Rendering (Part 1) – Flexport Engineering”