Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Update input value from mobx store with debounce

I have a MobX store and 2 Components, connected to the same value:

import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';

const store = makeAutoObservable({
  value: 0,
  setValue: (v) => {
    this.value = v;
  },
});

const ComponentOne = observer(() => {
  function handleOnChange(e) {
    store.setValue(e.target.value);
  }

  return <input value={store.value} onChange={handleOnChange} />;
});

const ComponentTwo = observer(() => {
  function handleOnChange(e) {
    store.setValue(e.target.value);
  }

  return <input value={store.value} onChange={handleOnChange} />;
});

I need:

  1. Changing the input value of <ComponentOne/> should cause the input value in <ComponentTwo/> to be updated from the new store value
  2. Storing data into MobX storage from Components should be done with debounce.
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

My Solution:

import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';
import { useDebouncedCallback } from 'use-debounce';

const store = makeAutoObservable({
  value: 0,
  setValue: (v) => {
    this.value = v;
  },
});

export function useStoreValue() {
  const storeValue = store.value;
  const setStoreValue = store.setValue;
  const [value, setValue] = useState(storeValue);

  // eslint-disable-next-line object-curly-newline
  const debouncedSetStoreValue = useDebouncedCallback(setStoreValue, 350, { maxWait: 1000 });

  useEffect(
    () => {
      if (storeValue !== value) {
        debouncedSetStoreValue(value);
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [value]
  );

  useEffect(() => {
    setValue(storeValue);
  }, [storeValue]);

  return [value, setValue];
}

const ComponentOne = observer(() => {
  const [value, setValue] = useStoreValue();

  function handleOnChange(e) {
    setValue(e.target.value);
  }

  return <input value={value} onChange={handleOnChange} />;
});

const ComponentTwo = observer(() => {
  const [value, setValue] = useStoreValue();

  function handleOnChange(e) {
    setValue(e.target.value);
  }

  return <input value={value} onChange={handleOnChange} />;
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!