• Stars
    star
    4,181
  • Rank 10,360 (Top 0.3 %)
  • Language
  • Created over 8 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A description of the conceptual model of React without implementation burden.

React - Basic Theoretical Concepts

This document is my attempt to formally explain my mental model of React. The intention is to describe this in terms of deductive reasoning that lead us to this design.

There may certainly be some premises that are debatable and the actual design of this example may have bugs and gaps. This is just the beginning of formalizing it. Feel free to send a pull request if you have a better idea of how to formalize it. The progression from simple -> complex should make sense along the way without too many library details shining through.

The actual implementation of React.js is full of pragmatic solutions, incremental steps, algorithmic optimizations, legacy code, debug tooling and things you need to make it actually useful. Those things are more fleeting, can change over time if it is valuable enough and have high enough priority. The actual implementation is much more difficult to reason about.

I like to have a simpler mental model that I can ground myself in.

Transformation

The core premise for React is that UIs are simply a projection of data into a different form of data. The same input gives the same output. A simple pure function.

function NameBox(name) {
  return { fontWeight: 'bold', labelContent: name };
}
'Sebastian Markbåge' ->
{ fontWeight: 'bold', labelContent: 'Sebastian Markbåge' };

Abstraction

You can't fit a complex UI in a single function though. It is important that UIs can be abstracted into reusable pieces that don't leak their implementation details. Such as calling one function from another.

function FancyUserBox(user) {
  return {
    borderStyle: '1px solid blue',
    childContent: [
      'Name: ',
      NameBox(user.firstName + ' ' + user.lastName)
    ]
  };
}
{ firstName: 'Sebastian', lastName: 'Markbåge' } ->
{
  borderStyle: '1px solid blue',
  childContent: [
    'Name: ',
    { fontWeight: 'bold', labelContent: 'Sebastian Markbåge' }
  ]
};

Composition

To achieve truly reusable features, it is not enough to simply reuse leaves and build new containers for them. You also need to be able to build abstractions from the containers that compose other abstractions. The way I think about "composition" is that they're combining two or more different abstractions into a new one.

function FancyBox(children) {
  return {
    borderStyle: '1px solid blue',
    children: children
  };
}

function UserBox(user) {
  return FancyBox([
    'Name: ',
    NameBox(user.firstName + ' ' + user.lastName)
  ]);
}

State

A UI is NOT simply a replication of server / business logic state. There is actually a lot of state that is specific to an exact projection and not others. For example, if you start typing in a text field. That may or may not be replicated to other tabs or to your mobile device. Scroll position is a typical example that you almost never want to replicate across multiple projections.

We tend to prefer our data model to be immutable. We thread functions through that can update state as a single atom at the top.

function FancyNameBox(user, likes, onClick) {
  return FancyBox([
    'Name: ', NameBox(user.firstName + ' ' + user.lastName),
    'Likes: ', LikeBox(likes),
    LikeButton(onClick)
  ]);
}

// Implementation Details

var likes = 0;
function addOneMoreLike() {
  likes++;
  rerender();
}

// Init

FancyNameBox(
  { firstName: 'Sebastian', lastName: 'Markbåge' },
  likes,
  addOneMoreLike
);

NOTE: These examples use side-effects to update state. My actual mental model of this is that they return the next version of state during an "update" pass. It was simpler to explain without that but we'll want to change these examples in the future.

Memoization

Calling the same function over and over again is wasteful if we know that the function is pure. We can create a memoized version of a function that keeps track of the last argument and last result. That way we don't have to reexecute it if we keep using the same value.

function memoize(fn) {
  var cachedArg;
  var cachedResult;
  return function(arg) {
    if (cachedArg === arg) {
      return cachedResult;
    }
    cachedArg = arg;
    cachedResult = fn(arg);
    return cachedResult;
  };
}

var MemoizedNameBox = memoize(NameBox);

function NameAndAgeBox(user, currentTime) {
  return FancyBox([
    'Name: ',
    MemoizedNameBox(user.firstName + ' ' + user.lastName),
    'Age in milliseconds: ',
    currentTime - user.dateOfBirth
  ]);
}

Lists

Most UIs are some form of lists that then produce multiple different values for each item in the list. This creates a natural hierarchy.

To manage the state for each item in a list we can create a Map that holds the state for a particular item.

function UserList(users, likesPerUser, updateUserLikes) {
  return users.map(user => FancyNameBox(
    user,
    likesPerUser.get(user.id),
    () => updateUserLikes(user.id, likesPerUser.get(user.id) + 1)
  ));
}

var likesPerUser = new Map();
function updateUserLikes(id, likeCount) {
  likesPerUser.set(id, likeCount);
  rerender();
}

UserList(data.users, likesPerUser, updateUserLikes);

NOTE: We now have multiple different arguments passed to FancyNameBox. That breaks our memoization because we can only remember one value at a time. More on that below.

Continuations

Unfortunately, since there are so many lists of lists all over the place in UIs, it becomes quite a lot of boilerplate to manage that explicitly.

We can move some of this boilerplate out of our critical business logic by deferring execution of a function. For example, by using "currying" (bind in JavaScript). Then we pass the state through from outside our core functions that are now free of boilerplate.

This isn't reducing boilerplate but is at least moving it out of the critical business logic.

function FancyUserList(users) {
  return FancyBox(
    UserList.bind(null, users)
  );
}

const box = FancyUserList(data.users);
const resolvedChildren = box.children(likesPerUser, updateUserLikes);
const resolvedBox = {
  ...box,
  children: resolvedChildren
};

State Map

We know from earlier that once we see repeated patterns we can use composition to avoid reimplementing the same pattern over and over again. We can move the logic of extracting and passing state to a low-level function that we reuse a lot.

function FancyBoxWithState(
  children,
  stateMap,
  updateState
) {
  return FancyBox(
    children.map(child => child.continuation(
      stateMap.get(child.key),
      updateState
    ))
  );
}

function UserList(users) {
  return users.map(user => {
    continuation: FancyNameBox.bind(null, user),
    key: user.id
  });
}

function FancyUserList(users) {
  return FancyBoxWithState.bind(null,
    UserList(users)
  );
}

const continuation = FancyUserList(data.users);
continuation(likesPerUser, updateUserLikes);

Memoization Map

Once we want to memoize multiple items in a list memoization becomes much harder. You have to figure out some complex caching algorithm that balances memory usage with frequency.

Luckily, UIs tend to be fairly stable in the same position. The same position in the tree gets the same value every time. This tree turns out to be a really useful strategy for memoization.

We can use the same trick we used for state and pass a memoization cache through the composable function.

function memoize(fn) {
  return function(arg, memoizationCache) {
    if (memoizationCache.arg === arg) {
      return memoizationCache.result;
    }
    const result = fn(arg);
    memoizationCache.arg = arg;
    memoizationCache.result = result;
    return result;
  };
}

function FancyBoxWithState(
  children,
  stateMap,
  updateState,
  memoizationCache
) {
  return FancyBox(
    children.map(child => child.continuation(
      stateMap.get(child.key),
      updateState,
      memoizationCache.get(child.key)
    ))
  );
}

const MemoizedFancyNameBox = memoize(FancyNameBox);

Algebraic Effects

It turns out that it is kind of a PITA to pass every little value you might need through several levels of abstractions. It is kind of nice to sometimes have a shortcut to pass things between two abstractions without involving the intermediates. In React we call this "context".

Sometimes the data dependencies don't neatly follow the abstraction tree. For example, in layout algorithms you need to know something about the size of your children before you can completely fulfill their position.

Now, this example is a bit "out there". I'll use Algebraic Effects as proposed for ECMAScript. If you're familiar with functional programming, they're avoiding the intermediate ceremony imposed by monads.

function ThemeBorderColorRequest() { }

function FancyBox(children) {
  const color = raise new ThemeBorderColorRequest();
  return {
    borderWidth: '1px',
    borderColor: color,
    children: children
  };
}

function BlueTheme(children) {
  return try {
    children();
  } catch effect ThemeBorderColorRequest -> [, continuation] {
    continuation('blue');
  }
}

function App(data) {
  return BlueTheme(
    FancyUserList.bind(null, data.users)
  );
}

More Repositories

1

react.dev

The React documentation website
TypeScript
11,041
star
2

react-transition-group

An easy way to perform animations when a React component enters or leaves the DOM
JavaScript
10,160
star
3

react-router-redux

Ruthlessly simple bindings to keep react-router and redux in sync
JavaScript
7,808
star
4

react-modal

Accessible modal dialog component for React
JavaScript
7,350
star
5

react-rails

Integrate React.js with Rails views and controllers, the asset pipeline, or webpacker.
JavaScript
6,746
star
6

react-router-tutorial

JavaScript
5,523
star
7

rfcs

RFCs for changes to React
5,502
star
8

server-components-demo

Demo app of React Server Components.
JavaScript
4,242
star
9

react-codemod

React codemod scripts
JavaScript
4,164
star
10

react-docgen

A CLI and library to extract information from React component files for documentation generation purposes.
TypeScript
3,646
star
11

react-tutorial

Code from the React tutorial.
JavaScript
3,290
star
12

react-tabs

An accessible and easy tab component for ReactJS.
JavaScript
3,089
star
13

react-chartjs

common react charting components using chart.js
JavaScript
2,928
star
14

react-future

Specs & docs for potential future and experimental React APIs and JavaScript syntax.
JavaScript
2,819
star
15

express-react-views

This is an Express view engine which renders React components on server. It renders static markup and *does not* support mounting those views on the client.
JavaScript
2,734
star
16

react-a11y

Identifies accessibility issues in your React.js elements
JavaScript
2,343
star
17

React.NET

.NET library for JSX compilation and server-side rendering of React components
C#
2,293
star
18

react-autocomplete

WAI-ARIA compliant React autocomplete (combobox) component
JavaScript
2,165
star
19

react-art

React Bridge to the ART Drawing Library
JavaScript
1,994
star
20

react-php-v8js

PHP library that renders React components on the server
PHP
1,326
star
21

react-magic

Automatically AJAXify plain HTML with the power of React. It's magic!
JavaScript
947
star
22

zh-hans.react.dev

React documentation website in Simplified Chinese
TypeScript
909
star
23

core-notes

Weekly meeting notes from the React core team
900
star
24

ko.react.dev

React documentation website in Korean
TypeScript
715
star
25

ru.react.dev

React documentation website in Russian / Официальная русская версия сайта React
TypeScript
699
star
26

pt-br.react.dev

🇧🇷 React documentation website in Portuguese (Brazil)
TypeScript
484
star
27

react-lifecycles-compat

Backwards compatibility polyfill for React class components
JavaScript
459
star
28

react-gradual-upgrade-demo

Demonstration of how to gradually upgrade an app to a new version of React
JavaScript
421
star
29

id.react.dev

(Work in progress) React documentation website in Indonesian
TypeScript
312
star
30

react-timer-mixin

TimerMixin provides timer functions for executing code in the future that are safely cleaned up when the component unmounts
JavaScript
308
star
31

es.react.dev

React documentation website in Spanish / Documentación del sitio web de React en Español
TypeScript
283
star
32

translations.react.dev

Nexus of resources and tools for translating the React docs.
JavaScript
260
star
33

ja.react.dev

React documentation website in Japanese
TypeScript
258
star
34

react-static-container

Renders static content efficiently by allowing React to short-circuit the reconciliation process.
JavaScript
223
star
35

fa.react.dev

(Work in progress) React documentation website in Persian
TypeScript
190
star
36

tr.react.dev

React documentation website in Turkish
TypeScript
165
star
37

ar.react.dev

React documentation website in Arabic 📘⚛️ — وثائق React باللغة العربية
TypeScript
138
star
38

uk.react.dev

🇺🇦 React documentation website in Ukrainian / Офіційна українська версія сайту React
TypeScript
134
star
39

hi.react.dev

(Work in progress) React documentation website in Hindi
TypeScript
115
star
40

zh-hant.react.dev

(Work in progress) React documentation website in Traditional Chinese
TypeScript
106
star
41

bn.react.dev

(Work in progress) React documentation website in Bengali
TypeScript
102
star
42

fr.react.dev

Version française du site de documentation officiel de React
TypeScript
98
star
43

vi.react.dev

(Work in progress) React documentation website in Vietnamese
TypeScript
89
star
44

react-bower

[DISCONTINUED] Bower package for React
JavaScript
69
star
45

legacy.reactjs.org

An archived copy of the legacy React documentation website
JavaScript
62
star
46

bn.reactjs.org

(Work in progress) React documentation website in Bengali
JavaScript
54
star
47

ta.reactjs.org

(Work in progress) React documentation website in Tamil
JavaScript
52
star
48

pl.react.dev

React documentation website in Polish
TypeScript
49
star
49

az.react.dev

🇦🇿 React documentation website in Azerbaijani
TypeScript
43
star
50

rackt-codemod

Codemod scripts for Rackt libraries
JavaScript
40
star
51

th.reactjs.org

(Work in progress) React documentation website in Thai
JavaScript
40
star
52

mn.react.dev

(Work in progress) React documentation website in Mongolian
TypeScript
38
star
53

uz.reactjs.org

(Work in progress) React documentation website in Uzbek
TypeScript
36
star
54

de.react.dev

(Work in progress) React documentation website in German
TypeScript
35
star
55

ml.react.dev

(Work in progress) React documentation website in Malayalam
TypeScript
32
star
56

si.reactjs.org

(Work in progress) React documentation website in Sinhala
JavaScript
32
star
57

it.react.dev

(Work in progress) React documentation website in Italian
TypeScript
32
star
58

be.react.dev

(Work in progress) React documentation website in Belarusian
TypeScript
30
star
59

ur.reactjs.org

(⚠️ Beta Docs Translation only) React documentation website in Urdu. Check details in https://github.com/reactjs/ur.reactjs.org/issues/1#issuecomment-949791355
TypeScript
29
star
60

he.react.dev

(Work in progress) React documentation website in Hebrew
TypeScript
28
star
61

ku.reactjs.org

(Work in progress) React documentation website in Kurdish
JavaScript
28
star
62

ml.reactjs.org

(Work in progress) React documentation website in Malayalam
JavaScript
25
star
63

ur.react.dev

(Work in progress) React documentation website in Urdu
TypeScript
25
star
64

el.reactjs.org

(Work in progress) React documentation website in Greek
JavaScript
25
star
65

hu.react.dev

Hungarian 🇭🇺 React ⚛ documentation 📚 / React magyar dokumentációja
TypeScript
25
star
66

gu.react.dev

(Work in progress) React documentation website in Gujarati
TypeScript
24
star
67

pt-PT.reactjs.org

(Work in progress) React documentation website in Portuguese (Portugal) 🇵🇹
JavaScript
23
star
68

ne.reactjs.org

(Work in progress) React documentation website in Nepali
JavaScript
23
star
69

gu.reactjs.org

(Work in progress) React documentation website in Gujarati
JavaScript
22
star
70

te.reactjs.org

(Work in progress) React documentation website in Telugu
JavaScript
22
star
71

hy.reactjs.org

(Work in progress) React documentation website in Armenian - https://hy.reactjs.org
JavaScript
21
star
72

km.reactjs.org

(Work in progress) React documentation website in Central Khmer
JavaScript
20
star
73

bg.reactjs.org

(Work in progress) React documentation website in Bulgarian
JavaScript
16
star
74

ro.reactjs.org

(Work in progress) React documentation website in Romanian
JavaScript
16
star
75

si.react.dev

(Work in progress) React documentation website in Sinhala
TypeScript
14
star
76

kn.reactjs.org

(Work in progress) React documentation website in Kannada
JavaScript
13
star
77

tl.reactjs.org

(Work in progress) React documentation website in Tagalog
TypeScript
13
star
78

ka.reactjs.org

(Work in progress) React documentation website in Georgian
JavaScript
11
star
79

sv.reactjs.org

(Work in progress) React documentation website in Swedish
JavaScript
9
star
80

te.react.dev

(Work in progress) React documentation website in Telugu
TypeScript
9
star
81

sw.react.dev

(Work in progress) React documentation website in Swahili
TypeScript
9
star
82

nl.reactjs.org

(Work in progress) React documentation website in Dutch
JavaScript
8
star
83

ta.react.dev

(Work in progress) React documentation website in Tamil
TypeScript
8
star
84

ca.reactjs.org

(Work in progress) React documentation website in Catalan
JavaScript
7
star
85

lt.reactjs.org

(Work in progress) React documentation website in Lithuanian
JavaScript
6
star
86

ht.reactjs.org

(Work in progress) React documentation website in Haitian Creole
JavaScript
5
star
87

sr.reactjs.org

(Work in progress) React documentation website in Serbian
TypeScript
5
star
88

is.react.dev

(Work in progress) React documentation website in Icelandic
TypeScript
4
star
89

kk.react.dev

🇰🇿 React documentation website in Kazakh / React сайтының ресми қазақша нұсқасы
TypeScript
4
star
90

cs.react.dev

(Work in progress) React documentation website in Czech
TypeScript
4
star
91

sq.reactjs.org

(Work in progress) React documentation website in Albanian
TypeScript
3
star
92

sr.react.dev

(Work in progress) React documentation website in Serbian
TypeScript
3
star
93

reactjs.github.io

HTML
2
star
94

my.reactjs.org

(Work in progress) React documentation website in Burmese
JavaScript
2
star
95

lo.react.dev

(Work in progress) React documentation website in Lao
TypeScript
2
star
96

fi.react.dev

(Work in progress) React documentation website in Finnish
TypeScript
2
star
97

sw.reactjs.org

(Work in progress) React documentation website in Swahili
JavaScript
2
star
98

mk.react.dev

(Work in progress) React documentation website in Macedonian
TypeScript
1
star
99

tg.reactjs.org

(Work in progress) React documentation website in Tajik
TypeScript
1
star