DEV Community

Discussion on: Do you need a State Management Library?

Collapse
 
link2twenty profile image
Andrew Bone

That is interesting. I try to use a few states as possible myself though, of course, still use a few.

For instance it's common to see a snippet like

  const [input, setInput] = useState();

  const displayValue = () => {
    console.log(input);
  }

  return (
    <>
      <input value={input} onChange={({target}) => setInput(target.value)} />
      <button onClick={displayValue}>Display</button>
    </>
  )
Enter fullscreen mode Exit fullscreen mode

Which takes the state away from the input and stores it in React. The only problem with this is it now takes process time, even though it's only a small amount, between each key stroke.

I'm much more likely to do something like

  const input = useRef(null);

  const displayValue = () => {
    const { current: el } = input;
    console.log(el.value);
  }

  return (
    <>
      <input ref={input} />
      <button onClick={displayValue}>Display</button>
    </>
  )
Enter fullscreen mode Exit fullscreen mode

This has the exact same outcome but will only need process time when the button is pressed rather than on every key stroke.