ID photo of Ciro Santilli taken in 2013 right eyeCiro Santilli OurBigBook logoOurBigBook.com  Sponsor 中国独裁统治 China Dictatorship 新疆改造中心、六四事件、法轮功、郝海东、709大抓捕、2015巴拿马文件 邓家贵、低端人口、西藏骚乱
Website: reactjs.org
React officially recommends that you use Next.js[ref], so just do it. It just sets up obvious missing functionality from raw React.
React feels like a good. But it also feels impossible to use/learn sometimes.
Its main design goal is to reduce DOM changes to improve rendering times.
And an important side effect of that is that it becomes easier to do stuff of the type:
  • user creates a new comment that appears on screen without page reload
  • comment has a delete button, which is JavaScript callback activated
and then the new comment easily gets the callback attached to it.
And it also ends up naturally doubling as a template engine.
But React can also be extremely hard to use. It can be very hard to know what you can and cannot do sometimes, then you have to stop and try to understand how react works things better:The biggest problem is that it is hard to automatically detect such errors, but perhaps this is the same for other frontend stuff. Though when doing server-side rendering, the setup should really tell you about such errors, so you don't just discover them in production later on.
Is is also very difficult to understand precisely why hooks run a certain number of times.
Examples under: react.
How React works bibliography:
Video 1.
React for the Haters in 100 Seconds by Fireship (2022)
Source.

React error

words: 2 articles: 1
Minimal reproduction: stackoverflow.com/questions/62336340/cannot-update-a-component-while-rendering-a-different-component-warning/70317831#70317831

React example

words: 100 articles: 2
Minimal React hello world example. As you click:
  • one counter increments every time
  • the other increments every two clicks
By opening a web inspector, you can see that only modified elements get updated. So we understand that JSX parses its "HTML-like" into a tree, and then propagates updates on that tree.
By looking at the terminal, we see that render() does get called every time the button is clicked, so the tree of elements does get recreated every time. But then React diffes thing out and only updates things in the DOM where needed.
react/hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<p><a href="https://cirosantilli.com/_file/react/hello.htmlhttps://cirosantilli.com/react">https://cirosantilli.com/_file/react/hello.html</a></p>
<div id="root"></div>
<script type="text/babel">
class Main extends React.Component {
  constructor(props) {
    super(props)
    console.log('Main.constructor')
    this.state = {n: 0}
  }

  render() {
    console.log('Main.render')
    return (
      <div>
        <button
          onClick={
            () => {
              console.log('onClick')
              this.setState((state, props) => ({
                n: state.n + 1
              }))
            }
          }>Click me</button>
        <div>n = {this.state.n}</div>
        <div>n/2 = {Math.floor(this.state.n / 2)}</div>
      </div>
    )
  }
}
ReactDOM.createRoot(document.getElementById('root')).render(<React.StrictMode><Main /></React.StrictMode>)
</script>
</body>
</html>
Failed attempt at minimizing nodejs/next/ref-twice outside of Next.js.
react/ref-twice.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<p><a href="https://cirosantilli.com/_file/react/ref-twice.html">https://cirosantilli.com/_file/react/ref-twice.html</a></p>
<div id="root"></div>
<script type="text/babel">
const { StrictMode, useState, useEffect, useRef } = React

function complexExternalLibraryFunctionWithoutCleanup(elem, cb) {
  elem.addEventListener('click', () => {
    cb()
  })
}

function Main(props) {
  const [text, setText] = useState('')
  const [myint, setMyint] = useState(0)
  const ref = useRef(null)
  function incIt() {
    setMyint(i => i+1)
  }
  useEffect(() => {
    if (ref.current) {
      complexExternalLibraryFunctionWithoutCleanup(ref.current, incIt)
    }
  }, [])
  return <div>
    <div><input value={text} onChange={e => setText(e.target.value)} placeholder='Type here' /></div>
    <div>You typed: {text}</div>
    <div><button ref={ref}>Click me after typing something! If unfixed, it will increment twice!</button></div>
    <div><button onClick={incIt}>Click me to increment!</button></div>
    <div>{myint}</div>
  </div>
}
ReactDOM.createRoot(document.getElementById('root')).render(<StrictMode><Main /></StrictMode>)
</script>
</body>
</html>

React DOM manipulation

words: 108 articles: 2
Dummy example of using a React ref This example is useless and to the end user seems functionally equivalent to react/hello.html.
It does however serve as a good example of what react does that is useful: it provides a "clear" separation between state and render code (which becomes once again much less clear in React function components.
Notably, this example is insane because at:
<button onClick={() => {
  elem.innerHTML = (parseInt(elem.innerHTML) + 1).toString()
we are extracing state from some random HTML string rather than having a clean JavaScript variable containing that value.
In this case we managed to get away with it, but this is in general not easy/possible.
react/ref-click-counter.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ref click counter</title>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Main extends React.Component {
  constructor(props) {
    super(props)
    console.log('Main.constructor')
    this.counterElem = null
  }

  render() {
    console.log('render')
    return (
      <div>
        <button onClick={() => {
          console.log('onClick')
          elem = this.counterElem
          elem.innerHTML = (parseInt(elem.innerHTML) + 1).toString()
        }}>
          Click me
        </button>
        <div
          ref={
            (elem) => {
              console.log(`ref callback ${elem}`)
              this.counterElem = elem
            }
          }
        >
          0
        </div>
      </div>
    )
  }
}

ReactDOM.render(
  <Main/>,
  document.getElementById('root')
)
</script>
</body>
</html>
React function component version of react/ref-click-counter.html using useRef.
react/ref-click-counter-func.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ref click counter</title>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function Main() {
  console.log('Main')
  const counterElem = React.useRef(null)
  return (
    <div>
      <button onClick={() => {
        console.log('onClick')
        const elem = counterElem.current
        elem.innerHTML = (parseInt(elem.innerHTML) + 1).toString()
      }}>
        Click me
      </button>
      <div
        ref={
          (elem) => {
            counterElem.current = elem
          }
        }
      >
        0
      </div>
    </div>
  )
}
ReactDOM.render( <Main/>, document.getElementById('root'))
</script>
</body>
</html>

React class vs function component

words: 59 articles: 6
React function components do produce shorter code. But they are also impossible to understand without knowing what is their corresponding class component.
Hooks were introduced much after classes, and just require less code, so everyone is using them now instead of classes.

React function component

words: 20 articles: 4

React hook

words: 20 articles: 3
useEffect
words: 20
This should only be used for things that happen outside of the state that React trackes, e.g. window event handlers.
Examples:

Next.js

words: 867 articles: 5
Framework built on top of React.
Officially recommended by React[ref]:
Recommended Toolchains
If you’re building a server-rendered website with Node.js, try Next.js.
gothinkster/realworld blog example by Ciro Santilli: node Express Sequelize Next.js realworld example app.
Basically what this does is to get server-side rendering just working by React, including hydration, which is a good thing.
Next.js sends the first pre-rendered HTML page along with the JavaScript code. Then, JavaScript page switches just load the API data.
Next.js does this nicely by forcing you to provide page data in a serialized JSON format, even when rendering server-side (e.g. the return value of getServerSideProps). This way, it is also able to provide either the full HTML, or just the JSON.
Some general downsides:
  • it does feel like they don't document deployment very well however, especially non-Vercel options, which is the company behind Next.js. I'm unable to find how to use a non Vercel CDN with ISR supposing that is possible.
  • Next.js is very opinionated, and like any opinionated library it is sometimes hard to know why something is/isn't happening, and sometimes it is hard/impossible to do what you want with it unless they add support. They have done good progress, but even as of 2022, some aspects just feel so immature, some major-looking use cases are not very well done.
In theory, Next.js could be the "ultimate frontend framework". It does have a lot of development difficulties that need to be ironed out, but the general concepts, and things it tries to integrate, including e.g. webpack, TypeScript, etc. are good. Maybe the question is when will someone put it together with an amazing backend library and dominate and finally put an end to the infinite number of Js Frameworks!
In-tree examples at: github.com/vercel/next.js/tree/canary/examples
canary is their master: github.com/vercel/next.js/issues/3211
In order to offer its amazing features, Next.js is also extremely opinionated, which means that if something wasn't designed to be possible, it basically isn't.
No prerender with custom server? It forces you to write your API with next as well? Or does it mean something else?
TODO can it statically generate pages that are created at runtime? E.g. if I create a new blog post, will it automatically upload a static page? It seems that yes, and that this is exactly what Incremental Static Regeneration means:However, Ciro can't find any mention of how to specify where the pages are uploaded to... this is pat of the non-Vercel deployment problem.
Can't ISR prerenter by URL query parameters:That plus the requirement to have one page per file under pages/ leads to a lot of useless duplication, because then you are forced to place the URL parameters on the pathnames.
"Module not found: Can't resolve 'fs'" Hell. The main reason this happens seems to be the that in a higher order component, webpack can't determine if callbacks use the require or not to remove it from frontend code. Fully investigated and solved at:
Overviews:
TODO answer:

Next.js example

words: 379 articles: 3
Our examples are located under nodejs/next:
Solved ones:
The goal of this example is to understand when states and effects happen when changing between different routes that use the same component.
Behavior is follows:
This is likely because in React the state kept in the virtual DOM structure, and identical structure implies identical state. So when we change from post 1 to 2, we still have a Post object, and state is unchanged.
Next if we click:
then the count is back to 0. This is because we changed the Post object in the DOM to Index and back, which resets everything.
This example also illustrates how to prevent this from happening with useEffect.
Bibliography:
This is a minimal reproducible example for the terrible problem of external effects applying twice to refs for effects that are not idempotent and thus blowup if applied twice.
The issue is currently discussed at: react.dev/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed (archive) which says "you need to cleanup the thing yourself". web.archive.org/web/20240720100401/https://react.dev/learn/synchronizing-with-effects#subscribing-to-events is also says that for the specific case of addEventListener.
But that's annoying! Can't we just somehow tell if we applied twice or not to avoid having to implement a cleanup? What if a third party system does not provide a cleanup at all?
Is the correct solution to just just have a useEffect with empty dependency list? Seems to be good according to posts and to ESLint!
Tried to do a React only reproduction at: react/ref-twice.html.
Bibliography:
Ciro Santilli's questions:
In this example we attempt to inject React elements into statically rendered HTML coming from the server, and properly hydrate them.
Questions by Ciro Santilli:
Bibliography:
github.com/cirosantilli/node-express-sequelize-nextjs-realworld-example-app

Ancestors (10)

  1. List of front-end web frameworks
  2. Front-end web framework
  3. Web framework
  4. Web technology
  5. Software
  6. Computer
  7. Information technology
  8. Area of technology
  9. Technology
  10. Home

Synonyms (2)