react-color-palette icon indicating copy to clipboard operation
react-color-palette copied to clipboard

Implement useColor to reload state from props

Open ClusterH opened this issue 3 years ago • 1 comments

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 avatar May 16 '22 20:05 ClusterH

@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

raiseandfall avatar May 20 '22 20:05 raiseandfall

Implemented in v7

Wondermarin avatar Aug 03 '23 19:08 Wondermarin

Awesome! Cannot wait to use it.

ClusterH avatar Aug 03 '23 20:08 ClusterH