Skip to content

Commit b8538ba

Browse files
Pascal-SoMadoshakalaka
authored andcommitted
move check to should_render_fn
1 parent 2b22bcd commit b8538ba

1 file changed

Lines changed: 10 additions & 16 deletions

File tree

packages/yew/src/functional/hooks/use_reducer.rs

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -274,18 +274,7 @@ where
274274
let should_render_fn = should_render_fn.clone();
275275
let mut val = val.borrow_mut();
276276
let next_val = (*val).clone().reduce(action);
277-
278-
// Check if the reduce action just returned the same `Rc` again instead of producing
279-
// a new one.
280-
// NOTE: here we make the assumption that an unchanged address implies that the
281-
// "identity" of the `Rc` is unchanged. This assumption is valid here because we
282-
// still keep the old Rc around. But if we were to instead move the old Rc into
283-
// the `reduce` function, then the address could be reused and the object inside
284-
// the Rc might be different. The `rc_was_reused` variable is thus only meaningful
285-
// as long as we use a `clone` before `reduce`.
286-
let rc_was_reused = Rc::ptr_eq(&val, &next_val);
287-
288-
let should_render = !rc_was_reused && should_render_fn(&next_val, &val);
277+
let should_render = should_render_fn(&next_val, &val);
289278
*val = next_val;
290279

291280
should_render
@@ -332,8 +321,8 @@ where
332321
///
333322
/// This hook will trigger a re-render whenever the reducer function produces a new `Rc` value upon
334323
/// receiving an action. If the reducer function simply returns the original `Rc` then the component
335-
/// will not re-render. See [`use_reducer_eq`] if you want the component to first compare the old and
336-
/// new state and only re-render when the state actually changes.
324+
/// will not re-render. See [`use_reducer_eq`] if you want the component to first compare the old
325+
/// and new state and only re-render when the state actually changes.
337326
///
338327
/// To cause a re-render even if the reducer function returns the same `Rc`, take a look at
339328
/// [`use_force_update`].
@@ -421,7 +410,7 @@ where
421410
T: Reducible + 'static,
422411
F: FnOnce() -> T,
423412
{
424-
use_reducer_base(init_fn, |_, _| true)
413+
use_reducer_base(init_fn, |a, b| !address_eq(a, b))
425414
}
426415

427416
/// [`use_reducer`] but only re-renders when `prev_state != next_state`.
@@ -434,5 +423,10 @@ where
434423
T: Reducible + PartialEq + 'static,
435424
F: FnOnce() -> T,
436425
{
437-
use_reducer_base(init_fn, T::ne)
426+
use_reducer_base(init_fn, |a, b| !address_eq(a, b) && a != b)
427+
}
428+
429+
/// Check if two references point to the same address.
430+
fn address_eq<T>(a: &T, b: &T) -> bool {
431+
std::ptr::eq(a as *const T, b as *const T)
438432
}

0 commit comments

Comments
 (0)