0
0
Vueframework~10 mins

Custom refs with customRef in Vue - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the function needed to create a custom ref in Vue.

Vue
import { [1] } from 'vue';
Drag options to blanks, or click blank then click option'
AcustomRef
Bref
Creactive
Dcomputed
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'ref' instead of 'customRef' for creating custom refs.
Importing 'reactive' or 'computed' which are different APIs.
2fill in blank
medium

Complete the code to define a custom ref that debounces updates by 300ms.

Vue
const debounced = customRef((track, trigger) => {
  let timeout;
  return {
    get() {
      [1]();
      return value;
    },
    set(newValue) {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        value = newValue;
        trigger();
      }, 300);
    }
  };
});
Drag options to blanks, or click blank then click option'
Atrack
Btrigger
CclearTimeout
DsetTimeout
Attempts:
3 left
💡 Hint
Common Mistakes
Calling 'trigger()' inside get instead of 'track()'.
Not calling any function inside get, so reactivity breaks.
3fill in blank
hard

Fix the error in the custom ref setter to correctly update the value and trigger reactivity.

Vue
set(newValue) {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    [1] = newValue;
    trigger();
  }, 300);
}
Drag options to blanks, or click blank then click option'
Atrigger
BnewValue
Cvalue
Dtimeout
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to 'newValue' which is the parameter, not the internal variable.
Calling 'trigger()' before updating the value.
4fill in blank
hard

Fill both blanks to create a custom ref that logs when it is read and written.

Vue
const loggerRef = customRef(([1], [2]) => {
  let value = '';
  return {
    get() {
      console.log('Value read');
      [1]();
      return value;
    },
    set(newValue) {
      console.log('Value written:', newValue);
      value = newValue;
      [2]();
    }
  };
});
Drag options to blanks, or click blank then click option'
Atrack
Btrigger
Cvalue
DnewValue
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of track and trigger.
Using variable names instead of functions for tracking and triggering.
5fill in blank
hard

Fill all three blanks to create a custom ref that only triggers updates if the new value is different.

Vue
const stableRef = customRef(([1], [2]) => {
  let value = null;
  return {
    get() {
      [1]();
      return value;
    },
    set(newValue) {
      if (newValue !== value) {
        value = newValue;
        [2]();
      }
    }
  };
});
Drag options to blanks, or click blank then click option'
Atrack
Btrigger
Cvalue
DnewValue
Attempts:
3 left
💡 Hint
Common Mistakes
Triggering updates even when the value is unchanged.
Not calling track in get, breaking reactivity.