betula / use-between

Sharing state between React components
MIT License
285 stars 11 forks source link

can we support params? #38

Closed zoffyzhang closed 1 year ago

zoffyzhang commented 1 year ago

it may looks like this:


const useCounter = (defaultValue1, defaultValue2) => {
  const [count1, setCount1] = useState(defaultValue1);
  const [count2, setCount2] = useState(defaultValue2);
  const inc1 = useCallback(() => setCount1(c => c + 1), []);
  const inc2 = useCallback(() => setCount2(c => c + 1), []);
  return {
    count1,
    count2,
    inc1,
    inc2
  };
};

const useSharedCounter = (defaultValue1, defaultValue2) => useBetween(useCounter, defaultValue1, defaultValue2);
betula commented 1 year ago

Hi @zoffyzhang,

Nice to meet you!)

There is no such functionality in the library, but you can achieve what you need with a few lines of code!

import { useBetween } from 'use-between';

export function useBetweenTweaked(hook, ...defaults) {
  if (!useBetweenTweaked[0]) {
    useBetweenTweaked[0] = new Map();
  }
  const map = useBetweenTweaked[0];
  if (!map.has(hook)) {
    map.set(hook, () => hook(...defaults));
  }
  const hookWithDefaults = map.get(hook);
  return useBetween(hookWithDefaults);
}

Demonstration on StackBlitz

export default function App() {
  const { count1, count2, inc1, inc2 } = useBetweenTweaked(useCounter, 10, 15);

  return (
    <div>
      <p>Count1: {count1}</p>
      <p>Count2: {count2}</p>
      <p>
        <button onClick={inc1}>+</button>
        <button onClick={inc2}>+</button>
      </p>
    </div>
  );
}

Now you can use "useBetweenTweaked" throughout your code and pass initialization parameters as needed.

Have a Great day and Cool code!

betula commented 1 year ago

Improved version of tweak for better compatibility with using useBetween hook together on one project.

export function useBetweenTweaked(hook, ...defaults) {
  if (!useBetweenTweaked[0]) {
    useBetweenTweaked[0] = new Map();
  }
  const map = useBetweenTweaked[0];
  if (!map.has(hook)) {
    map.set(hook, defaults.length ? () => hook(...defaults) : hook);
  }
  const hookWithDefaults = map.get(hook);
  return useBetween(hookWithDefaults);
}
zoffyzhang commented 1 year ago

thanks for so much help, it's very kind of you!