HN user

uryga

943 karma

she/her

meet.hn/city/de-Berlin

Socials:

- x.com/lubieowoce

- github.com/lubieowoce

---

Posts1
Comments621
View on HN

AFAIK there's no magic to React.memo. It's basically a shorthand for useMemo that takes the props as the dependency.

Pedantic note: this isn't quite true. memo() also allows a second `arePropsEqual` argument that useMemo doesn't have. Also, memo() compares individual prop values, while useMemo() can only look at the whole props object (which would be "fresh" on every render -- it's a diffferent object, even if it has the same values). So it's not like you can easily reimplement memo() via useMemo(). But of course, conceptually they are pretty close :)

Why did they not include other companies

AFAIK: the initial stages of the project involved Vercel and Shopify [edit: and Gatsby]. these companies maintain frameworks and hosting solutions for them, which makes them good partners to work on full-stack features like this. notably, the convention ("use client") came about based on early feedback from Shopify.

the reason to work with framework authors first is that RSC requires a high degree of coordination/wiring across client code, server code, and the bundler. React itself only implements a couple of low-level primitives that need to be wired together by something like a framework to actually do anything useful

expecting all third-party packages, React-related or not, to buy into the "use client" directive

AFAIK: non-react code has no reason to care about this directive. and on the react side, couldn't you make the same complaint about most breaking changes?

But their routing things locks you into NextJS as a framework.

I'm confused by this -- how is a framework supposed to offer routing in a way that doesn't "lock you in"? are you "locked into" React Router if you use that? what's the alternative?

RSC locks you into [Vercel's] hosting solution

how? you can self-host it if you want.

I would like to write a component, not have to think about where it is running in most cases

you can keep doing this, just put "use client" in the file, Next will SSR them just like it used to. (SSR is an "emulated client" in this model. admittedly, the naming is a bit confusing)

but for some things, you want a guarantee that it only runs on the server, and then you can use server components :) i believe this is also why useState & friends are disallowed there -- they fundamentally don't make sense for stuff that'll only ever run server-side.

zero functionality has been removed from class components

yes, exactly!

They use them because they are idiomatic React

right, and do you think it'd be easy for a feature to become idiomatic if it wasn't an improvement over the previous patterns?

Apps (as in, mobile apps) cannot be rendered on the sever

yes and no. sure, you can't do standard SSR like for websites. but i've seen a number of spins[1] on "Server-driven UI", meaning "server defines the app views as a big blob of JSON". usually, it's payload looking something like this:

  [
    { "type": "Heading", "text": "Our cool products" },
    { "type": "List", "children": [
      { "type": "ProductCard", "id": 123, },
      { "type": "ProductCard", "id": 456, }
      ...
    ] }
  ]
the app "interprets" this and displays the corresponding components in the specified arrangement.

the kicker is that, in a sense, RSC is just a less ad-hoc way to do this kind of thing! instead of `type` tags you get "client references", React handles the relevant parsing/serialization, and a lot of other good stuff on top. it's also quite seamless w.r.t writing components -- react does a very good job of abstracting away all the serialization business. and importantly, you can have an actual ecosystem of RSC packages around it, which a bespoke in-house method of doing this won't have.

now, RSC for react native has barely even been teased, but i'll bet good money that they have at least a prototype somewhere. and yeah, of course this would require your app to be in React Native. but that's the selling point -- IF all your stuff is in react, you get a bunch of power and some good DX.

---

[1] some examples off the top of my head:

- Facebook (not public, described by an employee): https://twitter.com/acdlite/status/1632217463772393473

- AirBnb: https://medium.com/airbnb-engineering/a-deep-dive-into-airbn...

- a Polish site called allegro.pl, though I can't find the conf talk about it right now...

TypeScript is a little unique in that its core type system is much more structural than nominal (even more so than Haskell)

I'm a bit confused by the point about Haskell here -- IME Haskell's type system is pretty strictly nominal, not a lot of structural typing there

good luck! it's quite fun :)

another term that might be useful is "GADT" - it's kinda like a weaker form of DT, more easily expressible in, uh, normal languages. the C# one i linked is really more like a GADT, bc it all stays at the type level w/o bringing "normal" values into it. another way to do it would be a sealed class with a private constructor + static methods:

  class Foo<T> {
    private Foo(...)
    static Foo<int> Bar() { ... }
    static Foo<string> Zap() { ... }
  }
(or sth like that, i don't really do C#!)

so that way you can have the type param and use it to track something, but limit what can be put there - in this case, only int or string. type-safe syntax trees are a common case for sth like this (though in that case you'd probably go for an abstract base + subclasses, like in the link).

i haven't used scala, but from the looks of it, yeah, "path-dependent types" are a narrow subset of full dependent types, intended for stuff like this exact use case :D

there's things you can do to track list length at the type level, but it usually involves putting your data in a special-purpose linked-list thingy: https://docs.idris-lang.org/en/latest/tutorial/typesfuns.htm...

(the `S` and `Z` refer to peano-style natural numbers)

although if you go that way, you can actually get a lot of that without dependent types! here's an example i found of someone doing a similar construction in C#: http://www.javawenti.com/?post=631496

last but not least, in TS you can use the builtin support for arrays as tuples and just do:

  type AtLeastTwo<T> = [_1: T, _2: T, ...rest: T[]]
which looks very nice, but it's pretty much only doable because the type system has specific support for array stuff like this, so not a really general solution.

while you probably can do this with dependent types, i'd imagine GP means something along the lines of typescript's structural typing, i.e.

  const post = {
    id: 123,
    content: "...",
    published: true,
  }
  // TS infers the type of `post` to be an unnamed "map-ish" type: 
  // { id: number, content: string, published: boolean }
JS objects are map-like, and this one is "heterogenous" in that the values are of different types (unlike most maps in statically typed langs, which need to be uniform). this just "structural typing", the easier way to do stuff like this.

now, dependent types allow you to express pretty much arbitrary shapes of data, so you can do heterogenous collections as well. i haven't read about it enough to do a map, but a list of tuples (equivalent if you squint) is "easy" enough:

  [
    ("id", 123),
    ("content", "..."),
    ("published", True),
  ]
in Idris, you could type it as something like this:
  -- a function describing what type the values of each key are
  postKeyValue : String -> Type
  postKeyValue k =
    case k of
      "id" -> Int
      "content" -> String
      "published" -> Bool
      _ -> Void  -- i.e. "no other keys allowed"
  
  -- now we're gonna use postKeyValue *at the type level*.

  type Post = List (k : String ** postKeyValue k)

  -- "a Post is a list of pairs `(key, val)` where the type of each `val` is given by applying `postKeyValue` to `key`.
  -- (read `**` like a weird comma, indicating that this is a "dependent pair")
more on dependent pairs: https://docs.idris-lang.org/en/latest/tutorial/typesfuns.htm...

in general if you want to learn more about DT's, i'd probably recommend looking at a language like Idris with "native support" for them. backporting DT's onto an existing typesystem usually makes them much harder to read/understand that they actually are (and don't get me wrong, they're mindbending enough on their own).

if you don't want to bother with that, i'd look at Typescript - it's combination of "literal types", "type guards" and "function overloads" can get you some of the power of DT's. see this article for some examples: https://www.javiercasas.com/articles/typescript-dependent-ty...

they allow as many operations as you need, just pass in a "method name" :)

  const p = Point(3, 5)
  p('getX') // 3
  p('up', 11)('toString') // "Point(3, 16)"


  const Point = (x, y) => (method, ...args) => {
    switch (method) {
      case 'getX': return x;
      case 'getY': return y;
      case 'toString': return `Point(${x}, ${y})`
      case 'up': return Point(x, y+args[0]);
      // ...
    }
  }
(unfortunately statically typing this statically requires... some work, either sth like [typescript overloads + literal types] or full on dependent types)

'useSyncExternalStore()' -- Gack!

Now...that "little" it's-not-a-framework-it's-a-library whose scope is supposed to be confined to just the "view" part of MVC (by which I mean: "React") is inserting it's tentacles [...] into the _model_.

useSyncExternalStore doesn't care about what you do in your model. it's for connecting your view to your model in a way that doesn't give you inconsistent states when concurrent-rendering-funkiness happens.

you could even say that useSyncExternalStore exists because React maintainers want people to be able to use whatever state-manager they want (instead of useState/useReducer/whatever) -- uSES was necessary to enable that in 18.

Go 1.18 4 years ago

are there any languages that do this? Rust's `?` is similar but the propagation is explicit

Go 1.18 4 years ago

But where they really shine, like in the mapping example, isn't possible in Go.

oh yeah, definitely! Go's version of EaV with multiple returns is pretty lackluster compared to a proper Result type. afaict it's kind of "the worst of both worlds" -- all of the boilerplate of plumbing errors manually w/ none of the benefits.

Go 1.18 4 years ago

But I also don't know any languages where errors _aren't_ values

(look, i know you understand how exceptions work, please bear with me)

yes, Exception objects are technically values, but you don't return them to the caller; you throw them to the, uh, catcher. basically, you get a special, second way of returning something that bypasses the normal one! but in the EaV approach, errors just are returned like every other thing.

the uniformity of EaV comes in handy when doing generic things like mapping a function over a collection - don't have to worry if something will throw, because it's just a value! and that lets you go to some pretty powerful places w.r.t abstraction: see e.g. haskells `traverse`.

but yeah, EaV needs some syntactic sugar to reach ergonomic par with exceptions, otherwise you get if-err-not-nil soup :P

Go 1.18 4 years ago

distinguishing `Some(null)` and `None` is often considered a feature of Optional ;)

to use a tired example: when getting a value out of a map via some `myMap.get(key)`, you may want to distinguish "not present" = `None` and "present, with value null" = `Some(null)`

the right solution is to just not have nulls in the first place, then there's no problem ;)

that's fair, i was in a spicy mood.

there's "esoteric" as in fundamentally complicated, and """esoteric""" as in syntax that's unfamiliar but easily explained w/ a quick web search.

i believe "it's nicer to express some things this way" is a very important practical benefit. for me, "being expressive for experienced users" is ultimately more important to optimize for than """learnablility""", scare quotes intended. because beginners will be beginners for a while, and then they won't. (i dislike e.g. Go for this reason, but let's not get sidetracked)

(before you or someone else asks: i've tutored many beginner/first-time programmers, and yes, i still think a bit of syntactic sugar won't hurt them)

yeah, that's not really explained in the article, and it's not explained in the `ast` docs either [1]. for reference, the full list of assignment targets is:

         -- the following expression can appear in assignment context
         | Attribute(expr value, identifier attr, expr_context ctx)
         | Subscript(expr value, expr slice, expr_context ctx)
         | Starred(expr value, expr_context ctx)
         | Name(identifier id, expr_context ctx)
         | List(expr* elts, expr_context ctx)
         | Tuple(expr* elts, expr_context ctx)
perhaps it's just neater to just have the context there on every one of them.

also, from a pragmatic standpoint, when actually processing the AST and analyzing it semantically, you'll pretty much always going to be handling expressions and patterns (= rvalues/lvalues) differently, bc they mean completely different things! and having the context right there makes it more convenient to handle. so like, when designing an AST datatype, you could just as well not include the context in Name() and it'd be fine, but the python `ast` module's primary usecase is compiling the AST to bytecode, where it's more convenient to just have that info around, so that's what they did.

[1] https://docs.python.org/3/library/ast.html#ast.Load

JSFuck (2012) 5 years ago

IME, code on prod rarely ships with a sourcemap. and as far as i can tell, GP is talking about other people's minified code, not something where they control the build process

  y %>% f(x, ., z)  ===  f(x, y, z)
R lets you do macro-ish things at at runtime [1], and `.` is a valid variable name [2]. so %>% can just evaluate the AST of its right argument in an environment with `. = a`.

(it's probably a bit more involved because %>% also supports

  a %>% f(b)  ===  f(a, b)
in which case %>% has to do some AST surgery to splice another argument in front of `b`.)

---

[1] https://en.wikipedia.org/wiki/Fexpr

[2] think `_` in python etc. R uses dots instead of underscores

TypeScript [...] adds to the bundle size.

tbh i haven't checked, but isn't the transpilation step for typescript just stripping out the type annotations? TSC is build-time only, so it won't factor into your bundle size, and i can't imagine the generated JS is significantly bigger than source -- if anything, it should be smaller ;p

yeah, the intersection of lazy evaluation and side-effects (incl. errors/exceptions) gets confusing, you definitely have to be there to help the student out of a jam. but i think it's useful to start out pretending R follows strict evaluation (because it's natural[1]) and then, once the student gets their bearings, you can introduce laziness.

---

[1] well, not "natural", but aligned with how math stuff is usually taught/done. in most cases, when asked to evaluate `f(x+1)`, you first do `x+1` and then take `f(_)` of that.