Skip to content

Commit 32dcd8a

Browse files
authored
Merge pull request #1055 from japgolly/topic/reusableRefs
Add `Reusability` for component refs
2 parents 3bf2439 + 5edc72b commit 32dcd8a

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

library/coreGeneric/src/main/scala/japgolly/scalajs/react/Reusability.scala

+8
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,14 @@ object Reusability extends ReusabilityMacros with ScalaVersionSpecificReusabilit
351351
implicit def refFullF[F[_], I, A, O]: Reusability[Ref.FullF[F, I, A, O]] =
352352
refRaw[A | Null].contramap(_.raw)
353353

354+
/** Updating a reference doesn't trigger a component re-rendering, nor is the current reference value considered for reusability.
355+
*
356+
* Any `map`/`contramap` functions installed in the ref are ignored for the sake of reusability. If this is undesirable, pass around
357+
* a [[Reusable]] ref instead.
358+
*/
359+
implicit def refToComponentF[F[_], I, R, O, C]: Reusability[Ref.ToComponentF[F, I, R, O, C]] =
360+
refFullF[F, I, R, O].narrow
361+
354362
/** Updating a reference doesn't trigger a component re-rendering, nor is the current reference value considered for reusability. */
355363
implicit def nonEmptyRefHandleF[F[_], A]: Reusability[NonEmptyRef.HandleF[F, A]] =
356364
refRaw[A].contramap(_.raw)

library/tests/src/test/scala/japgolly/scalajs/react/core/ReusabilityTest.scala

+20
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,13 @@ object ReusabilityTest extends TestSuite {
120120
assertEq(r.test(a, b), a == b)
121121
}
122122

123+
private def testByRef[A: Reusability](create: => A)(implicit l: Line): Unit = {
124+
val a = create
125+
val b = create
126+
assertEq(a ~=~ a, true)
127+
assertEq(a ~=~ b, false)
128+
}
129+
123130
override def tests = Tests {
124131

125132
"macros" - {
@@ -477,5 +484,18 @@ object ReusabilityTest extends TestSuite {
477484
assert(BigInt("10") ~=~ BigInt("10"))
478485
assert(BigInt("10") ~/~ BigInt("11"))
479486
}
487+
488+
"ref" - {
489+
"handle" - testByRef(Ref[Int]: Ref.Handle[Int])
490+
"simple" - testByRef(Ref[Int])
491+
"vdom" - testByRef(Ref.toAnyVdom())
492+
"scala" - testByRef(Ref.toScalaComponent(SampleComponent1.component))
493+
"js" - testByRef(Ref.toJsComponent(JsComponentEs6PTest.Component))
494+
}
495+
496+
"nonEmptyRef" - {
497+
"handle" - testByRef(NonEmptyRef[Int](6): NonEmptyRef.Handle[Int])
498+
"simple" - testByRef(NonEmptyRef[Int](6))
499+
}
480500
}
481501
}

0 commit comments

Comments
 (0)