changed 6 months ago
Linked with GitHub

函數式程式設計的前端誤用

caasih


  • React 十年經驗
  • 身為 web 仔,不見得能挑開發工具
  • 追求以最陽春的工具實踐 FP

JavaScript 很好


first-class function


const add = (a) => (b) => a + b const add3 = add(3)

sum types and product types


// list as a sum type type Result<T> = [T, undefined] | [undefined, Error] // list as a product type type Product = [ID, Name, Description, DateTime]

React 不好


  • 一開始主打自己是個從 FP 角度出發的 UI 工具
  • 卡在 v18 兩年了, 12/05 才出 v19

害怕 prop drilling


  • React 本來的優勢是「純粹」、「組合」
  • 有些 front-end 老師不喜歡一層一層傳遞資訊,鼓勵用 React context 傳遞資訊
  • 現在 React context 把元件焊在一起了

🤡


誤解 algebraic effects


try { makeFriends(arya, gendry); } handle (effect) { if (effect === 'ask_name') { resume with 'Arya Stark'; } }
  • Dan Abramov 在介紹 algebraic effects 的文章中舉了個想像的例子
  • 可以看出,本來 effect handler 應該是由外面提供的

  • 如果圍繞著 effect 打造應用,該要能抽換 effect handlers
  • 以 React 的設計來說,最簡單的方法是把 custom hooks 放在 React context 裡
  • React 生態圈沒有人這樣做,發明了別的各種方法來 mock effects

🤡


侷限的 CPS 變換


use is a React API that lets you read the value of a resource like a Promise or context.

const value = use(resource)

  • 本來就可以靠 useStateuseEffect 做出自己的 custom React hooks ,來替 Promise, Observable 或任意新結構做 CPS 變換
  • 現在這個 use 只能用在 Promise 和 React context 上

🤡


雞肋的 React compiler


React Compiler is a new compiler that we’ve open sourced to get early feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the Rules of React, so you don’t need to rewrite any code to use it.


  • 現在只能幫忙 memo function 或 value
  • 追究原因,來自於 React 團隊在 JS 不支援 one-shot delimited continuation 的情況下硬要推出自己的 effect system

🤡

Select a repo