Skip to content

Commit

Permalink
Add use_effect hook
Browse files Browse the repository at this point in the history
  • Loading branch information
matthunz committed Jan 20, 2024
1 parent 1975da7 commit 4af1c5c
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[workspace]
resolver = "2"
members = [
"crates/concoct",
"crates/concoct-web",
Expand Down
1 change: 1 addition & 0 deletions crates/concoct/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ full = []

[dependencies]
futures = "0.3.30"
rustc-hash = "1.1.0"
slotmap = "1.0.7"
tracing = "0.1.40"

Expand Down
3 changes: 3 additions & 0 deletions crates/concoct/src/hook/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
mod use_context;
pub use use_context::{use_context, use_provider};

mod use_effect;
pub use self::use_effect::use_effect;

mod use_ref;
pub use use_ref::use_ref;

Expand Down
20 changes: 20 additions & 0 deletions crates/concoct/src/hook/use_effect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use super::use_ref;
use rustc_hash::FxHasher;

use std::hash::{Hash, Hasher};

pub fn use_effect(dependencies: impl Hash, effect: impl FnOnce()) {
let mut hasher = FxHasher::default();
dependencies.hash(&mut hasher);
let hash = hasher.finish();

let mut is_initial = false;
let last_hash = use_ref(|| {
is_initial = true;
hash
});

if is_initial || hash != *last_hash {
effect()
}
}

0 comments on commit 4af1c5c

Please sign in to comment.