Skip to content

Commit 5e3dadf

Browse files
committed
move check to should_render_fn
1 parent 11a4640 commit 5e3dadf

File tree

1 file changed

+10
-16
lines changed

1 file changed

+10
-16
lines changed

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

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -224,18 +224,7 @@ where
224224
let should_render_fn = should_render_fn.clone();
225225
let mut val = val.borrow_mut();
226226
let next_val = (*val).clone().reduce(action);
227-
228-
// Check if the reduce action just returned the same `Rc` again instead of producing
229-
// a new one.
230-
// NOTE: here we make the assumption that an unchanged address implies that the
231-
// "identity" of the `Rc` is unchanged. This assumption is valid here because we
232-
// still keep the old Rc around. But if we were to instead move the old Rc into
233-
// the `reduce` function, then the address could be reused and the object inside
234-
// the Rc might be different. The `rc_was_reused` variable is thus only meaningful
235-
// as long as we use a `clone` before `reduce`.
236-
let rc_was_reused = Rc::ptr_eq(&val, &next_val);
237-
238-
let should_render = !rc_was_reused && should_render_fn(&next_val, &val);
227+
let should_render = should_render_fn(&next_val, &val);
239228
*val = next_val;
240229

241230
should_render
@@ -277,8 +266,8 @@ where
277266
///
278267
/// This hook will trigger a re-render whenever the reducer function produces a new `Rc` value upon
279268
/// receiving an action. If the reducer function simply returns the original `Rc` then the component
280-
/// will not re-render. See [`use_reducer_eq`] if you want the component to first compare the old and
281-
/// new state and only re-render when the state actually changes.
269+
/// will not re-render. See [`use_reducer_eq`] if you want the component to first compare the old
270+
/// and new state and only re-render when the state actually changes.
282271
///
283272
/// To cause a re-render even if the reducer function returns the same `Rc`, take a look at
284273
/// [`use_force_update`].
@@ -366,7 +355,7 @@ where
366355
T: Reducible + 'static,
367356
F: FnOnce() -> T,
368357
{
369-
use_reducer_base(init_fn, |_, _| true)
358+
use_reducer_base(init_fn, |a, b| !address_eq(a, b))
370359
}
371360

372361
/// [`use_reducer`] but only re-renders when `prev_state != next_state`.
@@ -379,5 +368,10 @@ where
379368
T: Reducible + PartialEq + 'static,
380369
F: FnOnce() -> T,
381370
{
382-
use_reducer_base(init_fn, T::ne)
371+
use_reducer_base(init_fn, |a, b| !address_eq(a, b) && a != b)
372+
}
373+
374+
/// Check if two references point to the same address.
375+
fn address_eq<T>(a: &T, b: &T) -> bool {
376+
std::ptr::eq(a as *const T, b as *const T)
383377
}

0 commit comments

Comments
 (0)