{"id":16880119,"url":"https://github.com/mlhiter/mini-react","last_synced_at":"2025-08-02T08:34:28.644Z","repository":{"id":223007980,"uuid":"758951935","full_name":"mlhiter/mini-react","owner":"mlhiter","description":"a tutorial project about creating a mini-react","archived":false,"fork":false,"pushed_at":"2024-02-19T16:29:17.000Z","size":17,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-20T02:40:07.250Z","etag":null,"topics":["mini","react","tutorial"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mlhiter.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-02-17T15:01:14.000Z","updated_at":"2024-02-19T16:30:53.000Z","dependencies_parsed_at":"2024-02-19T04:29:31.699Z","dependency_job_id":"270c8e04-f61c-495e-870f-997b3826bc59","html_url":"https://github.com/mlhiter/mini-react","commit_stats":null,"previous_names":["mlhiter/mini-react"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/mlhiter/mini-react","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mlhiter%2Fmini-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mlhiter%2Fmini-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mlhiter%2Fmini-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mlhiter%2Fmini-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mlhiter","download_url":"https://codeload.github.com/mlhiter/mini-react/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mlhiter%2Fmini-react/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268355734,"owners_count":24237367,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-02T02:00:12.353Z","response_time":74,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mini","react","tutorial"],"created_at":"2024-10-13T15:57:21.491Z","updated_at":"2025-08-02T08:34:28.602Z","avatar_url":"https://github.com/mlhiter.png","language":"JavaScript","readme":"### Tutorial\n\nThis is a tutorial to build a mini-react.\n\nLearn from this website.[build-your-own-react](https://pomb.us/build-your-own-react/)\n\nThe following is a flat structure, it is recommended to read the linear structure in the tutorial.\n\nThe following is just reference.\n\n### Principle\n\n#### 1，JSX\n\nreact使用jsx描述界面。\n\njsx的形式：return后面的html代码，其实就是js里的html\n\n```js\nfunction Counter() {\n  const [state, setState] = React.useState(1)\n  return \u003ch1 onClick={() =\u003e setState((c) =\u003e c + 1)}\u003eCount: {state}\u003c/h1\u003e\n}\n```\n\n浏览器不认识jsx，所以我们需要转换jsx成为浏览器认识的样子。\n\n通过babel可以将jsx转换为我们想要的东西。比如react是将jsx转换为createElement函数调用形成的树。\n\n```jsx\nconst element =  \u003ch1 data\u003ehello world!\u003c/h1\u003e\n//transform by babel\nconst element = React.createElement(\"h1\",null,'Hello world!')\n```\n\n默认Babel将jsx转换为react的createElement，也可以自己自定义函数。\n\n比如我项目代码里：这个注释的意思就是告诉babel转换为**我自己定义的**React.createElement\n\n```jsx\n/**@jsx React.createElement */\nfunction Counter() {\n  const [state, setState] = React.useState(1)\n  return \u003ch1 onClick={() =\u003e setState((c) =\u003e c + 1)}\u003eCount: {state}\u003c/h1\u003e\n}\n```\n\n转换为函数调用之后，通过React.render()将其转换为真实DOM元素。\n\n#### 2，API\n\n项目里就设计了三个react的API：createElement用于babel转换jsx；render渲染真实DOM；useState是React Hooks的一个例子。\n\n##### 2.1 createElement\n\n**作用**：提供给babel的一个工具函数，告诉babel应该转换成为什么样子。\n\n这里项目逻辑是将children放入props里并对文本child进行标记。\n\n```jsx\n// @param {string} type -元素的类型，例如p，div\n// @param {Object} props -要传递给元素的属性对象，例如id，className\n// @param ...children 任意数量子元素，null/undefined/false，string，calling of React.createElement\nfunction createElement(type,props,...children){\n  return xxx\n}\n```\n\n##### 2.2 render\n\n**作用**：calling of React.createElement 转换为真实DOM\n\n```jsx\n// @param {ReactElement} element -要挂载的react元素\n// @param {HTMLElement} container -将element挂载到的父元素\nfunction render(element,container){\n}\n```\n\n##### 2.3 useState\n\n**作用**：基本hook一个\n\n```jsx\n// @param initial -初始值\n// @return useState,setState\nfunction useState(initial){\n  return [state,setState]\n}\n```\n\n#### 3，React特性（难点）\n\n##### 3.1 并发模式\n\n**背景：**\n\n在常规思路下我们在render函数里会递归调用子元素的render渲染。一旦我们开始渲染，递归不会停止直到渲染出完整的元素树。如果元素树很大就会阻塞主线程导致浏览器无法执行优先级更高的行为（比如用户输入或者流畅的动画），他们必须等待渲染完成之后才能进行。\n\n**使用技术：**\n\n项目里使用：[requestIdleCallback](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/requestIdleCallback)，这个函数会在浏览器主线程空闲时期被调用。具体参考代码和MDN，比较简单的一个函数。\n\nReact现在实际使用：react之前使用requestIdleCallback，后来改为使用专门的调度包。\n\n**基本流程：**\n\n```jsx\nfunction workLoop(deadline) {\n  let shouldYield = false // 是否应该停止\n\n  while (nextUnitOfWork \u0026\u0026 !shouldYield) {\n    nextUnitOfWork = performUnitOfWork(nextUnitOfWork)\n    shouldYield = deadline.timeRemaining() \u003c 1 //预估剩余时间少于1ms，几乎可以断定只剩最后一次\n  }\n\n  // 当没有下一个工作单元并且存在工作根时提交结果，否则继续执行\n  if (!nextUnitOfWork \u0026\u0026 wipRoot) {\n    commitRoot()\n  }\n\n  requestIdleCallback(workLoop)\n}\n```\n\n##### 3.2 Fiber\n\n**背景：**\n\n当我们处于并发模式时，我们通过工作单元的方式进行。之前常规做法我们使用循环不需要考虑执行顺序，但是这时我们就需要考虑工作单元的执行顺序，此时我们就需要数据结构发挥作用了。\n\n**数据结构：Fiber Tree**\n\n每个element配备一个fiber，每个fiber都会是一个工作单元。\n\n在**performUnitOfWork**过程中，我们的每个工作单元的任务有三件事：\n\n1. 将元素添加到DOM\n2. 为元素的子元素创建fiber\n3. 选择下一个工作单元\n   1. 如果有child，选择第一个child\n   2. 如果没有child，选择第一个sibling\n   3. 如果没有child也没有sibling，选择第一个叔叔（parent的第一个sibling），没有则向上继续查找叔叔\n   4. 如果查找到根，render所有工作完成\n\n```jsx\n//fiber structure\ninterface Fiber{\n  type:string //element.type\n  props:string //element.props\n  parent?:Fiber //parent fiber\n  child?:Fiber //child fiber\n  sibling?:Fiber //sibling fiber(next one)\n  dom?: HTMLElement //dom tree,function component fiber donnot have dom\n  alternate:Fiber // previous fiber\n  effectTag:\"UPDATE\"||\"PLACEMENT\"||\"DELETION\" //tag\n}\n```\n\n##### 3.3 Function Components\n\n**与DOM不同之处：**\n\n- fiber来自function component而不是DOM node,简单的理解就是外面包了一层没有dom的fiber\n- children来自运行该函数而不是来自静态props\n\n```jsx\nfunction updateFunctionComponent(fiber) {\n  const children = [fiber.type(fiber.props)] //type为函数组件这个函数\n  reconcileChildren(fiber, children)\n}\n```\n\n之后还需要在commitWork函数里处理找不到DOM的情况\n\n- 当前找不到DOM则向上找\n- 删除时找不到DOM则向下找\n\n##### 3.4 Hooks\n\n```jsx\n// React Hooks: useState\nfunction useState(initial) {\n  const oldHook =\n    wipFiber.alternate \u0026\u0026\n    wipFiber.alternate.hooks \u0026\u0026\n    wipFiber.alternate.hooks[hookIndex]\n\n  const hook = { state: oldHook ? oldHook.state : initial, queue: [] }\n\n  // 上一个render里定义的操作在当前render执行\n  const actions = oldHook ? oldHook.queue : []\n  actions.forEach((action) =\u003e {\n    hook.state = action(hook.state)\n  })\n\n  // 点击之后就会触发监视器循环的继续进行进而rerender\n  const setState = (action) =\u003e {\n    hook.queue.push(action)\n    wipRoot = {\n      dom: currentRoot.dom,\n      props: currentRoot.props,\n      alternate: currentRoot,\n    }\n    nextUnitOfWork = wipRoot\n    deletions = []\n  }\n\n  wipFiber.hooks.push(hook)\n  hookIndex++\n\n  return [hook.state, setState]\n}\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmlhiter%2Fmini-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmlhiter%2Fmini-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmlhiter%2Fmini-react/lists"}