Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
F

focal

> 前端框架
Open source

Program user interfaces the FRP way.

731 stars0 likes3 views
WebsiteGitHub

About

Program user interfaces the FRP way.

Type safe, expressive and composable state management for React applications.

  • Represent the whole application state as an immutable and observable single source of truth.
  • Seamlessly embed observables into React components' layout.
  • Leverage the power of Rx.JS (and observables in general) to enrich and combine parts of application state, explicitly controlling the data flow.
  • Use lenses to decompose the application state into smaller parts, so you can isolate UI components in a clean way and manipulate application state effortlessly.
  • Write less code that is easier to understand.

Packages

@grammarly/focal - Type safe, expressive and composable state management for React applications. @grammarly/focal-atom - Type safe, expressive and composable state management for any application.

Example

Here's a typical example of a 'counter' UI component and how it fits within the whole application:

…

You can play with this example online on CodeSandbox.

There's also a more elaborate version of this example, as well as some other examples, in the examples directory.

Installation

bash
yarn add @grammarly/focal-atom @grammarly/focal
# or
yarn add @grammarly/focal-atom

or

bash
npm install --save @grammarly/focal-atom @grammarly/focal
# or
npm install --save @grammarly/focal-atom

It is important to satisfy the RxJS peer dependency (required for instanceof Observable tests to work correctly).

Also note, that for npm-based packages you will need npm 3.x. For Focal to work properly, you need to:

  • have the same version of RxJS installed in your package (listed as a peer dependency in Focal)
  • have RxJS installed in an npm 3.x way so that it is not duplicated in your app's node_modules and Focal's node_modules

Tutorial

The example above might be a bit too overwhelming. Let's go over the main concepts bit by bit.

Reactive variables

In Focal, state is stored in Atoms. Atom is a data cell that holds a single immutable value, which you can read and write to:

typescript
import { Atom } from '@grammarly/focal-atom'

// create an Atom with initial value of 0
const count = Atom.create(0)

// output the current value
console.log(count.get())
// => 0

// set 5 as the new value
count.set(5)

console.log(count.get())
// => 5

// modify the value: set a new value which is based on current value
count.modify(x => x + 1)

console.log(count.get())
// => 6

You can also track (get notified of) changes that happen to an Atom's value. In this sense, an Atom can be thought of as a reactive variable:

typescript
import { Atom } from '@grammarly/focal-atom'

const count = Atom.create(0)

// subscribe to changes of count's value, outputting a new value to the
// console each time
// NOTE how this will immediately output the current value
count.subscribe(x => {
  console.log(x)
})
// => 0

console.log(count.get())
// => 0

// set a new value – it will get written to the console output
count.set(5)
// => 5

count.modify(x => x + 1)
// => 6

Atom properties

Every atom is expected to satisfy these properties:

  1. When .subscribed to, emit the current value immediately.
  2. Don't emit a value if it is equal to the current value.

Single source of truth

Atoms are used as a source of application state in Focal. There are more than one way in which you can create an Atom, with Atom.create being the one that you use to create the application state root. Ideally, we want for the application state to come from a single source of truth. (We will talk about managing application state in this fashion below).

Although you can create as many Atoms through Atom.create as you need, it generally should be avoided. The problem with having several (or many) sources of application state is that you may end up with different sorts of dependencies between these state sources, and there is no way to update several Atoms at the same time. This can lead to inconsistency between the parts of your application state.

Data binding

We have learned how to create, change and track application state. Now, for it to be useful in a React user interface, we need a way to display this data.

Focal allows you to directly embed Atoms in JSX code. In practice, this works similar to data binding in frameworks like Angular. There are differences, though:

  • In Focal, you use regular code (TypeScript or JavaScript), and not a template engine syntax (like in Vue.js), to describe your data. There's no magic happening at the syntax level, so you can use all the standard language tools that you already have.
  • Since Focal data bindings are ordinary TypeScript (or JavaScript) expressions, you can continue using the same IDE features like autocompletion, go to definition, rename refactoring, find usages, etc. This makes UI layout code maintenance easier compared to a template engine.
  • You can also take advantage of your existing static analysis tools (e.g. the type checking of TypeScript compiler). This way, your UI code can be just as reliable as any other code.
  • The change of data (an Atom) triggers component render, and not the other way around (e.g. when component render triggers data evaluation). You also usually don't think about when a component should get rendered – this is handled automatically.

Let's see what it looks like in code:

typescript
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { F, Atom } from '@grammarly/focal'

// create our state
const count = Atom.create(0)

// define a stateless React component that will take
// an Atom in its props
const Counter = (props: { count: Atom }) =>
  
    {/* embed the state atom directly in JSX */}
    Count: {count}
  

// mount the component onto DOM
const root = createRoot(document.getElementById('test'))
root.render()

// => 

How is this different from regular React?

Instead of using a `

…

typescript // a spiced up version of the counter component const Counter = (props: { count: Atom }) =>

Count: {count}.
{/* say whether the count number is odd or even */}
That's an {count.view(x => x % 2 === 0 ? 'even' : 'odd')} number!

// =>

…

typescript const Counter = (props: { count: Atom }) => rgba(255, 0, 0, ${Math.min(16 * x, 255)})) }}

Count: {count}.
That's an {count.view(x => x % 2 === 0 ? 'even' : 'odd')} number!

// =>

…

typescript interface Lens { get(source: TSource): T set(newValue: T, source: TSource): TSource }


And an example usage:

```typescript
import { Lens } from '@grammarly/focal-atom'

// an object that we want to operate on
const obj = {
  a: 5
}

// our example lens that looks at the object's `a` property
const a = Lens.create(
  // provide the getter: returns the `a` property
  (obj: { a: number }) => obj.a,
  // and the setter: returns a new object with the `a` property updated to a new value
  (newValue, obj) => ({ ...obj, a: newValue })
)

// read through the lens
console.log(a.get(obj))
// => 5

// write through the lens
console.log(a.set(6, obj))
// => { a: 6 }

Note how we get a fresh object back when we use the .set method: as we're working without mutations, we create a new object when we want to .set some part of it through a lens.

This doesn't look very useful yet, though. After all, why don't we just do obj.a and { ...obj, a: 6 } every time we need to?

But imagine that your object is lot more complex than that (e.g. { a: { b: { c: 5 } } }), and that it's just a part of some even bigger object:

typescript
const bigobj = {
  one: { a: { b: { c: 5 } } },
  two: { a: { b: { c: 6 } } }
}

One powerful feature of lenses is that they can be composed (chained together). Assume you have defined a lens to drill down to the c property of the { a: { b: { c: 5 } } } object. Now you can reuse that to work on both (one and two) parts of the bigobj object:

typescript
// a lens that is focused on a deeply nested property `c` of an `{ a: { b: { c: 5 } } }` object
const abc: Lens = ...

// a lens that looks at the `one` part of `bigobj`
const one: Lens = ...

// a lens that looks at the `two` part of `bigobj`
const two: Lens = ...

// compose `one` and `two` with `abc` so we can work on `c` of `{ one: { a: { b: { c: 5 } } } }`
// and `{ two: { a: { b: { c: 5 } } } }`
const oneC = one.compose(abc)
const twoC = two.compose(abc)

console.log(oneC.get(bigobj))
// => 5

console.log(twoC.get(bigobj))
// => 6

console.log(oneC.set(7, bigobj))
// => { one: { a: { b: { c: 7 } } }, two: { a: { b: { c: 6 } } } }

Focal also gives you the ability to define these lenses quite conveniently:

typescript
// create the above lenses by providing key names
const abc = Lens.key()('a', 'b', 'c')

const one = Lens.key()('one')

const two = Lens.key()('two')

// Note the extra nullary call. It is there for better type inference. To create a type safe
// lens we need to tell the compiler both the type of source and the type of destination property.
// Unlike with Atom.lens, the compiler doesn't yet know the type of the source data, so we have to
// explicitly state it. The compiler then can easily infer the type of the destination property by
// its name.
//
// We need the nullary call because we have two generic type parameters, and want one of them
// explicit and another inferred. So the nullary call is there only to supply the type argument
// for the source data type.

…

typescript
import { Atom, Lens } from '@grammarly/focal-atom'

// create an atom to hold our object
const obj = Atom.create({
  a: 5
})

// create a lens to look at the `a` property of the object
const a = Lens.key()('a')

// create a lensed atom that will hold a value of the `a` property of our object
const lensed = obj.lens(a)

console.log(obj.get())
// => { a: 5 }

console.log(lensed.get())
// => 5

// set a new value to the lensed atom
lensed.set(6)

console.log(obj.get())
// => { a: 6 }

Note how the source atom's value has changed when we set a new value to the lensed atom – that's it. There's also a neat shortcut to create lensed atoms:

typescript
const lensed = obj.lens('a')

We don't need to explicitly create a Lens – atom's lens method already has a couple of overloads to create lensed atoms on the spot. Also note that we didn't need to add the typeof obj type annotation here: the compiler already knows the type of data we're operating on (from the type of obj, which in this case is `Atom }) =>

Count: {props.count}.

 props.count.modify(x => x + 1)}>
  Click again!

// the app component which takes the whole app state from the // state prop const App = (props: { state: Atom }) =>


And this concludes our tutorial on Focal basics!

Hopefully, it is now more clear how all of this comes together. Please also make sure to check out some of the [other examples](packages/examples) – build them and play around to get a better feel for what you can do.

# Framework?

Focal is not a framework, in the sense that you are not restricted to a particular way of writing your whole application. Focal has an imperative interface (remember that you can use the `.set` and `.modify` methods of atom) and can play nicely with React components of any nature. This means that using Focal is optional within different parts of the same application.

# Performance

Although we've yet to establish a comprehensive set of benchmarks, so far Focal has shown performance at least on par with plain React on examples such as TodoMVC.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptlensesreactrxjsstate-management

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架