react-codemirror2
react-codemirror2 copied to clipboard
avoid controlled vs uncontrolled components
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