Attach “class property” to Functional Component — React

Using closure

Yudi Supriyadi
1 min readAug 13, 2021

I got problem here.

File: Timeline.jsconst statefulService = new Service();function Timeline() {
if (!service.isFetched()) {
return <span>Memuat...</span>;
}
...
}

Using it multiple times we got unexpected result:

import Timeline from "./Timeline";function App() {
return (
<Timeline />
<Timeline />
)
}

Since const statefulService = new Service(); executed once after we imported Timeline.js file components got unexpected sharing service — and sharing state.

To solve that we can use Closure by create service each time new component created.

function Timeline()
{
const service = new Service();
return function Timeline() {
const [tweets, setTweets] = useState([]);
useEffect(() => {
service.get()
.then((tweets) => setTweets(tweets));
}, []);
if (!service.isFetched()) {
return <span>Memuat...</span>;
}
return (
<div>
{tweets.map((t) => (
<Tweet key={t.id} data={t} />
))}
</div>
);
};
};
export default function Helper(props) => {
const Comp = Timeline();
return <Comp {...props} />
}
Helper.displayName = "_";

Feels like class eh?

Do not forget to exclude “_” in react devtools.

Lets talk more about it.

Why you not useState instead?

const [service] = useState(new Service());

Service won’t changed but states inside it will.

How about useRef?
I don’t like “service.current” syntax yet we can alias it to a variable.

const service = useRef(new Service()).current;

Oh you correct! But closure solution gives us ability to share service to other component inside same closure. Feels like “private method” component eh?

--

--

No responses yet