in

useMergeState – 30 seconds of code


const useMergeState = (initialState = {}) => {
  const [value, setValue] = React.useState(initialState);

  const mergeState = newState => {
    if (typeof newState === 'function') newState = newState(value);
    setValue({ ...value, ...newState });
  };

  return [value, mergeState];
};
const MyApp = () => {
  const [data, setData] = useMergeState({ name: 'John', age: 20 });

  return (
    <>
      <input
        value={data.name}
        onChange={e => setData({ name: e.target.value })}
      />
      <button onClick={() => setData(({ age }) => ({ age: age - 1 }))}>
        -
      </button>
      {data.age}
      <button onClick={() => setData(({ age }) => ({ age: age + 1 }))}>
        +
      </button>
    </>
  );
};

ReactDOM.render(<MyApp />, document.getElementById('root'));


Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

GIPHY App Key not set. Please check settings

Welcome 2.0 — Discover the best places from your favorite people

PATA LAGNA LYRICS – RANJIT BAWA