React State Improvement

Viewed 60

Can we write the code in a shorter version?

For example:

function Account() {
  const [code, setCode] = useState('')
  
  return <input onChange={(e) => setCode(e.target.value)} />
}

Could we do it even more shorter like without creating new function? Like:

<input onChange={setCode} />

Some way?

Best!

1 Answers

You could use a custom useEventState helper that wraps React's useState and adds an additional setter to the tuple (array) it returns:

const useEventState = value => {
  const [ initialValue, directSetter ] = useState(value);
  
  return [
    initialValue,
    directSetter,
    e => directSetter(e.target.value)
  ];
}

I think it makes sense to also still return the original setter that takes a value directly. If you only set code through an onChange event, you could even replace it with the e.target.value one.

Here's a quick example (in which I added a button that uses the direct setter to show that's still useful to include):

function Account() {
  const [code, setCode, setCodeFromEvent] = useEventState('');
    
  const toUpper = () => {
    setCode(code.toUpperCase());
  }
  
  return (
    <div>
      <input value={code} onChange={setCodeFromEvent} />
      <p>Your code: {code}</p>
      <button onClick={toUpper}>To upper case</button>
    </div>
  );
}

ReactDOM.render(
  <Account />,
  document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script>
const { useState } = React;
const useEventState = value => {
  const [ initialValue, directSetter ] = useState(value);
  
  return [
    initialValue,
    directSetter,
    e => directSetter(e.target.value)
  ];
}
</script>

Related