Hide React.useState in function

Viewed 24

I am relearning React and thinking about an effective way to pass state between components. so far I would use something like let [currentValue, setValue] = React.useState(defaultValue); and pass currentValue and setValue to another Component. I am wondering if I can simplify that approach with a function UseState, see below. What might be flaws that I am missing? The proof of concept works at least.

import React from "react";

function UseState<T>(defaultValue: T) {
  let [currentValue, setValue] = React.useState(defaultValue);

  return function (value?: T): T {
    if (value === undefined) {
      return currentValue;
    }
    setValue(value);
    return value;
  };
}

interface FooProps {
  counter: (v?: number) => number;
}

function Foo({counter}: FooProps) {
  return (
    <strong
      onClick={() => {
        counter(counter() + 1);
      }}
    >
      count: {counter()}
    </strong>
  );
}

function FooHoc() {
  let Counter = UseState<number>(0);

  return (<div><Foo counter={Counter} /> : {Counter()}</div>)
}

export default function App() {
  return (
    <div className="App">
      <FooHoc />
    </div>
  );
}
0 Answers
Related