react-color-palette
react-color-palette copied to clipboard
Implement useColor to reload state from props
The Problem:
I made simple example to show the problem
const ColorParam: React.FC<{ value: string }> = ({ value }) => {
const [color, setColor] = useColor('hex', value)
return <ColorPicker width={240} height={120} color={color} onChange={setColor} hideHSV hideRGB dark alpha />
}
export default ColorParam
In here value is assign from props, and it does not update the state when props updated from parent component since useState is doing so in the React.
The Solution:
I suggest to use custom hook for useState in useColor.hook.ts
**Current : **
export function useColor<M extends keyof Color, C extends Color[M]>(
model: M,
initColor: C
): [Color, React.Dispatch<React.SetStateAction<Color>>] {
const [color, setColor] = useState(() => {
switch (model) {
case "hex":
.....
default:
return toColor("hex", "#121212");
}
});
return [color, setColor];
}
**Improvement : **
export function useColor<M extends keyof Color, C extends Color[M]>(
model: M,
initColor: C
): [Color, React.Dispatch<React.SetStateAction<Color>>] {
const [color, setColor] = useStateWithProps(() => {
switch (model) {
case "hex":
....
default:
return toColor("hex", "#121212");
}
});
return [color, setColor];
}
**Custom Hook : **
export const useStateWithProps = <T>(defaultValue: T) => {
const [value, setValue] = useState(() => defaultValue)
useEffect(() => {
setValue(defaultValue)
}, [defaultValue])
return [value, setValue] as const
}
@ClusterH thanks for the proposal, this would be huge. Do you think you could open a PR with it if that speeds up the process? @Wondermarin do you think that could go in soon if a PR is provided? Thanks all
Implemented in v7
Awesome! Cannot wait to use it.