react-codemirror2 icon indicating copy to clipboard operation
react-codemirror2 copied to clipboard

avoid controlled vs uncontrolled components

Open sibelius opened this issue 3 years ago • 0 comments

With hooks we can provide a single component, and let user control only some props, using this hook:

https://gist.github.com/sibelius/d44c23c1b50f2edb393718b0236dbb20

import { useState } from 'react';

export const useControlledState = <T extends any>(value: T, onChange?: (value: T) => void) => {
  const [uncontrolledValue, setUncontrolledValue] = useState(value);
  if (typeof onChange === 'function') {
    // Controlled version
    return [value, onChange];
  }
  // Uncontrolled version
  return [uncontrolledValue, setUncontrolledValue];
};

instead of using useState for controlled props, you just use useControlledState, and let user control it if he/she pass the onChange handler for the props

sibelius avatar Jul 24 '20 11:07 sibelius