Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blog 18 - useRef, useCallback, useMemo #18

Open
wants to merge 3 commits into
base: blog-17
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 1 addition & 55 deletions examples/hello-world/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,55 +1 @@
import {useState, useEffect} from 'react'
// function App() {
// const [num, updateNum] = useState(0)
// const len = 100

// console.log('num', num)
// return (
// <ul
// onClick={(e) => {
// updateNum((num: number) => num + 1)
// }}>
// {Array(len)
// .fill(1)
// .map((_, i) => {
// return <Child i={`${i} ${num}`} />
// })}
// </ul>
// )
// }

// function Child({i}) {
// return <p>i am child {i}</p>
// }

// export default App

const Item = ({i, children}) => {
for (let i = 0; i < 999999; i++) {}
return <span key={i}>{children}</span>
}

export default () => {
const [count, updateCount] = useState(0)

const onClick = () => {
updateCount(2)
}

useEffect(() => {
const button = document.querySelector('button')
setTimeout(() => updateCount((num) => num + 1), 1000)
setTimeout(() => button.click(), 1100)
}, [])

return (
<div>
<button onClick={onClick}>增加2</button>
<div style={{wordWrap: 'break-word'}}>
{Array.from(new Array(1000)).map((v, index) => (
<Item i={index}>{count}</Item>
))}
</div>
</div>
)
}
export {default} from './useCallback'
22 changes: 22 additions & 0 deletions examples/hello-world/src/ref/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {useState, useEffect, useRef} from 'react'

export default function App() {
const [isDel, del] = useState(false)
const divRef = useRef(null)

console.warn('render divRef', divRef.current)

useEffect(() => {
console.warn('useEffect divRef', divRef.current)
}, [])

return (
<div ref={divRef} onClick={() => del((prev) => !prev)}>
{isDel ? null : <Child />}
</div>
)
}

function Child() {
return <p ref={(dom) => console.warn('dom is:', dom)}>Child</p>
}
29 changes: 29 additions & 0 deletions examples/hello-world/src/useCallback/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {useState, useCallback} from 'react'

let lastFn

export default function App() {
const [num, update] = useState(1)
console.log('App render ', num)

const addOne = useCallback(() => update((n) => n + 1), [])
// const addOne = () => update((n) => n + 1)

if (lastFn === addOne) {
console.log('useCallback work')
}

lastFn = addOne

return (
<div>
<Cpn onClick={addOne} />
{num}
</div>
)
}

const Cpn = function ({onClick}) {
console.log('Cpn render')
return <div onClick={() => onClick()}>lll</div>
}
27 changes: 27 additions & 0 deletions examples/hello-world/src/useMemo/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {useState, useMemo} from 'react'

let lastCpn
// 方式1:App提取 bailout四要素
// 方式2:ExpensiveSubtree用memo包裹
export default function App() {
const [num, update] = useState(0)
console.log('App render ', num)

const Cpn = useMemo(() => <ExpensiveSubtree />, [])

if (lastCpn === Cpn) {
console.log('useMemo work')
}
lastCpn = Cpn
return (
<div onClick={() => update(num + 100)}>
<p>num is: {num}</p>
{Cpn}
</div>
)
}

function ExpensiveSubtree() {
console.log('ExpensiveSubtree render')
return <p>i am child</p>
}
25 changes: 20 additions & 5 deletions packages/react-dom/src/host_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use std::any::Any;
use std::cell::RefCell;
use std::rc::Rc;

use js_sys::{Function, global, Promise};
use js_sys::JSON::stringify;
use wasm_bindgen::JsValue;
use js_sys::{global, Function, Promise};
use wasm_bindgen::prelude::*;
use web_sys::{Node, window};
use wasm_bindgen::JsValue;
use web_sys::{window, Node};

use react_reconciler::HostConfig;
use shared::{log, type_of};
Expand Down Expand Up @@ -162,7 +162,14 @@ impl HostConfig for ReactDomHostConfig {
.is_function()
{
let closure_clone = closure.clone();
queueMicrotask(&closure_clone.borrow_mut().as_ref().unwrap().as_ref().unchecked_ref::<JsValue>());
queueMicrotask(
&closure_clone
.borrow_mut()
.as_ref()
.unwrap()
.as_ref()
.unchecked_ref::<JsValue>(),
);
closure_clone.borrow_mut().take().unwrap_throw().forget();
} else if js_sys::Reflect::get(&*global(), &JsValue::from_str("Promise"))
.map(|value| value.is_function())
Expand All @@ -179,7 +186,15 @@ impl HostConfig for ReactDomHostConfig {
c.forget();
} else {
let closure_clone = closure.clone();
setTimeout(&closure_clone.borrow_mut().as_ref().unwrap().as_ref().unchecked_ref::<JsValue>(), 0);
setTimeout(
&closure_clone
.borrow_mut()
.as_ref()
.unwrap()
.as_ref()
.unchecked_ref::<JsValue>(),
0,
);
closure_clone.borrow_mut().take().unwrap_throw().forget();
}
}
Expand Down
14 changes: 14 additions & 0 deletions packages/react-reconciler/src/begin_work.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ use std::rc::Rc;
use wasm_bindgen::JsValue;

use shared::derive_from_js_value;
use web_sys::js_sys::Object;

use crate::child_fiber::{mount_child_fibers, reconcile_child_fibers};
use crate::fiber::{FiberNode, MemoizedState};
use crate::fiber_flags::Flags;
use crate::fiber_hooks::render_with_hooks;
use crate::fiber_lanes::Lane;
use crate::update_queue::{process_update_queue, ReturnOfProcessUpdateQueue};
Expand Down Expand Up @@ -74,6 +76,15 @@ fn update_host_root(
work_in_progress.clone().borrow().child.clone()
}

fn mark_ref(current: Option<Rc<RefCell<FiberNode>>>, work_in_progress: Rc<RefCell<FiberNode>>) {
let _ref = { work_in_progress.borrow()._ref.clone() };
if (current.is_none() && !_ref.is_null())
|| (current.is_some() && !Object::is(&current.as_ref().unwrap().borrow()._ref, &_ref))
{
work_in_progress.borrow_mut().flags |= Flags::Ref;
}
}

fn update_host_component(
work_in_progress: Rc<RefCell<FiberNode>>,
) -> Option<Rc<RefCell<FiberNode>>> {
Expand All @@ -84,6 +95,9 @@ fn update_host_component(
derive_from_js_value(&ref_fiber_node.pending_props, "children")
};

let alternate = { work_in_progress.borrow().alternate.clone() };
mark_ref(alternate, work_in_progress.clone());

{
reconcile_children(work_in_progress.clone(), Some(next_children));
}
Expand Down
8 changes: 7 additions & 1 deletion packages/react-reconciler/src/child_fiber.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,12 @@ fn reconcile_single_text_node(
current = current_rc.borrow().sibling.clone();
}

let mut created = FiberNode::new(WorkTag::HostText, props.clone(), JsValue::null());
let mut created = FiberNode::new(
WorkTag::HostText,
props.clone(),
JsValue::null(),
JsValue::null(),
);
created._return = Some(return_fiber.clone());
Rc::new(RefCell::new(created))
}
Expand Down Expand Up @@ -235,6 +240,7 @@ fn update_from_map(
WorkTag::HostText,
props.clone(),
JsValue::null(),
JsValue::null(),
))))
};
} else if type_of(element, "object") && !element.is_null() {
Expand Down
Loading