Enhancing User Experience with Fast Transition Animations in React
Why Animation Matters
Adding animation and transition effects to your website’s components can significantly improve user experience. However, using heavy animation libraries can lead to slow performance due to the added overhead.
Introducing transition-hook
transition-hook is a lightweight Hooks library for creating animations in React. It is similar to the popular react-transition-group, but with a simpler syntax and better performance. Unlike full animation libraries like Framer Motion or react-spring, transition-hook does not animate elements automatically. Instead, it allows you to add animations to an element’s entrance and exit from the DOM using its lifecycle methods with CSS classes and styles.
How transition-hook Works
transition-hook leverages the series of lifecycle methods that are invoked when a component enters and exits the DOM. It uses these lifecycle methods to create transition stages that allow us to add animations to components with CSS classes and styles based on when the components mount and unmount.
Using transition-hook
The library exposes three React Hooks: useTransition
, useSwitchTransition
, and listTransition
. These Hooks transform a Boolean state into transition stages that can be invoked when a component mounts or unmounts after a specified duration.
useTransition
This Hook is useful for creating simple and linear animations. Here’s an example of a fade-in and fade-out animation using useTransition
:
import { useTransition } from 'transition-hook';
function Example() {
const [onOff, setOnOff] = useState(true);
const { stage, shouldMount } = useTransition(onOff, 300);
return (
<div>
{shouldMount && (
<div style={{
opacity: stage === 'enter'? 1 : 0,
transition: 'opacity 300ms'
}}>
<p>Hello World!</p>
</div>
)}
</div>
);
}
useSwitchTransition
This Hook animates elements based on state changes. It is useful for creating more complex animations. Here’s an example of an emoji switcher using useSwitchTransition
:
import { useSwitchTransition } from 'transition-hook';
function Example() {
const [isHappy, setIsHappy] = useState(true);
const transition = useSwitchTransition(isHappy, 300, 'default');
return (
<div>
{transition((state, stage) => (
<span
style={{
transform: stage === 'enter'? 'cale(1)' : 'cale(0)',
transition: 'transform 300ms'
}}
>
{state? '😊' : '😢'}
</span>
))}
</div>
);
}
listTransition
This Hook is useful for animating lists of items. Here’s an example of a list animation using listTransition
:
import { listTransition } from 'transition-hook';
function Example() {
const items = ['item1', 'item2', 'item3'];
const transition = listTransition(items, 300);
return (
<ul>
{transition((item, stage) => (
<li
style={{
opacity: stage === 'enter'? 1 : 0,
transition: 'opacity 300ms'
}}
>
{item}
</li>
))}
</ul>
);
}