Intro
A few days ago I was tasked with building a site with some parallax, scroll based animations. In order to make this happen I used the fantastic react-plx library. This was a task that was great use for a library because it handled a lot of the painstaking animation work quickly and was easy to setup.
The Code Situation
After some discussion we decided to only have the parallax effect be visible on desktop and render the components without animation on mobile. I was passing all my data into a parallax component which would render the parallax-ing element so I knew if I wanted to make the change I would have to make it here
// ParallaxAnimator.js
const ParallaxAnimator = ({ parallaxData, children }) => {
return (
<Plx parallaxData={parallaxData} className="parallax">
{children}
</Plx>
);
};
The solve seems pretty simple. Add some lines of code that measure the screen width and render the content either with or without the Plx
component accordingly.
// ParallaxAnimator.js
const ParallaxAnimator = ({ parallaxData, children }) => {
const [windowWidth, setWindowWidth] = useState(null);
const { mobileBreakpoint } = useContext(ThemeContext);
// logic to decide what to render on resize
useEffect(() => {
const handleResize = () => setWindowWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
});
// render without parallax component on resize
if (windowWidth < mobileBreakpoint) {
return <>{children}</>
}
return (
<Plx parallaxData={parallaxData} className="parallax">
{children}
</Plx>
);
};
However, my first instinct wasn't to write some fairly basic JS logic to do this myself. Instead of writing these extra 7 (!) lines of code, my first instinct was to reach for a library which left me with the following code which achieved the same result.
// ParallaxAnimator.js
const ParallaxAnimator = ({ parallaxData, children }) => {
const { mobileBreakpoint } = useContext(ThemeContext);
const isMobile = useMediaPredicate(mobileBreakpoint);
if (isMobile) {
return <>{children}</>;
}
return (
<Plx parallaxData={parallaxData} className="parallax">
{children}
</Plx>
);
};
The Question
Maybe this says more about me as a developer but I think it's a decent issue in the community as a whole. Is me using a library for this simple task the end of the world? No. But does it dilute my thinking and make me less aware of the tradeoffs involved in building a web application? I believe so. It also takes away a bit of the critical thinking skills that we should pride ourselves on as developers. We should enjoy making our own solutions even to simple problems such as this one.
So I pose the question, has library overuse, especially in React become too much the norm? I think I realized for me it has.
Top comments (1)
To answer the question posited in your title, the answer is a resounding NO