scniro / react-codemirror2

Codemirror integrated components for React
MIT License
1.66k stars 193 forks source link

avoid controlled vs uncontrolled components #201

Open sibelius opened 4 years ago

sibelius commented 4 years ago

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