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

102
Views
React State Improvement

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

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!