In React, we can write components as pure functions. However, the problem with this is that you can’t use it as stateful components because of the lack of lifecycle hooks and state. So, I wonder if is there any way to create stateful components without using classes.
Something that I found is the createClass
helper. But, React has moved this helper into their own package in the release 15.5.0
, link. Also, they recommend that you migrate them to JavaScript classes because classes are now the preferred way to create components in React. Therefore, I don’t think that using this helper could be a good idea.
On the other hand, Facebook recommends the use of High Order Components (HOCs) which is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature. But, I couldn’t find a way to create common stateful components without classes.
Has anyone gone through this? Is there any way to use React as a some purely functional solution?
4
Answers
Writing Stateful component without using classes is definitely a choice made by several developers. I recommend to use ‘recompose’ which has nice and easy implementation to write stateful components without class, yet apply state, both local and from store. Here is an example:
Maybe react-instance can become handy. Take a look at examples below.
Save state in local variable:
Save state in component state:
React supports this since version 16.8. From the documentation:
A simple example:
For an example of how to use lifecycles, check out
useEffect
I tried to create a simple stateful component named Comp without the usage of es6 classes.
Here is the code
Basically I’m linking the prototype of the Comp function (our stateful component) to the prototype object of React.Component and I pass down to it Comp’s props to initialize it properly. After that you can use every function of the React.Component object on the Comp.prototype. I used some just an example. I don’t know if this is the best way in the “most javascript” way to use react