From React To Preact In Seconds
So I decided to try out Preact after I heard it mentioned in an event that I attended earlier this year. I didn’t want to build a new project from scratch so I looked for a simple way to transit my old React project to it. At first I thought it would be a tedious one since I will have to change all occurences of react
to preact-compat
. Below is an outline of all I did.
Webpack to the rescue
While thinking of the changes I had to make, I remembered the resolve.alias
property in webpack. So I added the configuration to my webpack config
resolve: {
'alias': {
'react': 'preact-compat',
'react-dom': 'preact-compat',
'react-addons-test-utils': 'preact-test-utils',
'react-addons-css-transition-group': 'preact-css-transition-group'
}
}
Then I installed the modules by running
$ npm install -save preact preact-compat preact-test-utils preact-css-transition-group
Note:
- The version of my react module is 14.x
- I aliased
react-addons-test-utils
andreact-addons-css-transition-group
because I’m using the modules in my app.
Results
The size of my app before changing to preact is shown below
I got the result below after changing to preact
Gotchas
- When children is not supplied to a component, preact returns an empty array while react returns undefined. If a ternary like below is written,
props.children ? props.children : 'Do something else'
Preact returns nil while react returns Do something else
. This should be watched out for.
2. You may lose some capabilities of React but not likely as I’ve not lost any.
Conclusion
- Preact is a smaller version of react and it’s code can be easily read.
- Preact comes with some exciting features like Linked State and so on.
- Make sure to test your app thoroughly before shipping.
- Preact documentation is quite easy to read https://preactjs.com
If you liked this, click the 💚 below so other people will see this here on Medium. Also, if you have any questions or observations, use the comment section to share your thoughts/questions.
#9
Subscribe
Devcenter is a community driven network of verified Software Developers and Designers in Africa.