Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
React MUI Transitions Util
Next article icon

Animation and Transitions using React Hooks

Last Updated : 03 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Animations allows to control the elements by changing their motions or display. Animation is a technique to change the appearance and behaviour of various elements in web pages.

Transitions in CSS allow us to control the way in which transition takes place between the two states of the element. We can use the transitions to animate the changes and make the changes visually appealing to the user and hence, giving a better user experience and interactivity. In this article, we will learn simple animations and transitions using React hooks.

Handling animations in React using hooks like useEffect and useState along with CSS transitions or animation libraries provides a flexible and powerful way to create dynamic user interfaces.

Approach to Create Animations and Transitions using React Hooks:

We will be showing very simple examples of CSS animations and transitions on HTML elements and applying basic React hooks like useState and useEffect to manage the state of animation triggers, such as whether an element should be visible or hidden. The useEffect hook to control when animations should start or stop and maintain a incremental count. This could involve setting up timers (setInterval, setTimeout) or responding to changes in state.

Steps to Create React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app react-animation-transition

Step 2: After creating your project folder(i.e. react-animation-transition), move to it by using the following command:

cd react-animation-transition

Step 3: After creating the React application, Install the required package using the following command:

npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^6

Project Structure:

The updated dependencies in the package.json file

"dependencies": {
"@chakra-ui/react": "^2.8.2",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"framer-motion": "^6.5.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example 1: Write the code in the respective files. Conditionally apply CSS classes to elements based on state changes. This allows you to trigger animations using CSS transitions or keyframes.

The animation can be seen with the change in the color of the div text content. Initially the div content is visible but it is hidden after the button is clicked by the user.

CSS
/* App.css */ .btn-container {     display: flex;     margin: 1rem;     flex-direction: row; }  .btn {     padding: 5px;     margin: 20px;     cursor: pointer;     background-color: #FFFF;     border-radius: 10px;     font-weight: bold; }  /* The animation rule */ @keyframes myKeyframe {     0% {         background-color: red;     }      25% {         background-color: yellow;     }      50% {         background-color: blue;     }      100% {         background-color: green;     } }  /* The above rule is applied to this element*/ .animate {     width: 200px;     height: 200px;     background-color: red;     animation-name: myKeyframe;     animation-duration: 4s; } 
JavaScript
// App.js import {     ChakraProvider,     Text, Box, Flex, } from "@chakra-ui/react";  import { useState } from 'react'  import './App.css'   function App() {      const [visible, setVisible] = useState(true);      function hide() {         setVisible(false);     }     if (!visible) {         style.display = "none";     }     return (         <ChakraProvider>             <Box bg="lightgrey" w="100%" h="100%" p={4}>                  <Text                     color="#2F8D46" fontSize="2rem"                     textAlign="center" fontWeight="400"                     my="1rem"                 >                     GeeksforGeeks - React JS concepts                 </Text>                 <h3><b>React hooks with animation</b></h3>                 <br />                 <div className="animate">                     <div>A computer science portal for geeks designed                         for who wish to get hands-on Data Science.                         Learn to apply DS methods and techniques,                         and acquire analytical skills.</div>                     <button className="btn btn-container"                         onClick={hide}>                         Click this to hide                         <i className="" />{" "}                     </button>                 </div>              </Box>         </ChakraProvider>     ); };   export default App 

Start your application using the following command:

npm start

Output:

Example 2: Write the codes in the respective files. As the text Shadow is animated using the CSS keyframe rules, the count is incremented to demonstrate the useState and useEffect React hooks.

CSS
/* Styles.css */ h2 {     font-size: 36px;     font-weight: bold;     animation: textShadow 1s ease-in-out infinite alternate; }  @keyframes textShadow {     from {         text-shadow: 2px 2px #333;     }      to {         text-shadow: 10px 10px #333;     } } 
JavaScript
// App.js import {     ChakraProvider,     Text, Box, } from "@chakra-ui/react";  import React, { useState, useEffect } from 'react'  import './Styles.css'  function App() {     const [count, setCount] = useState(0);      useEffect(() => {         //Implementing the setInterval method         const interval = setInterval(() => {             setCount(count + 1);         }, 1000);          //Clearing the interval         return () => clearInterval(interval);     }, [count]);      return (         <ChakraProvider>             <Box bg="lightgrey" w="100%" h="100%" p={4}>                 <h1 style={{ color: "green" }}>                     GeeksforGeeks                 </h1>                 <Text                     color="#2F8D46" fontSize="2rem"                     textAlign="center" fontWeight="400"                     my="1rem"                 >                     React hooks with animation                 </Text>                 <h2>Animated text Shadow</h2>                 <h1>{count}</h1>             </Box>         </ChakraProvider>     ); };  export default App 

Output:

Example 3: The following code demonstrates gradient animation and displaying message using the useEffect React hook. The setTimeout function in JavaScript is a method used to introduce a delay before executing a specified function.

CSS
/* CSSheets.css */ h2 {     font-size: 36px;     font-weight: bold;     animation: gradientText 5s ease-in-out infinite; }  @keyframes gradientText {     0% {         color: red;     }      25% {         color: yellow;     }      50% {         color: blue;     }      100% {         color: green;     } } 
JavaScript
// App.js import {     ChakraProvider,     Text, Box, } from "@chakra-ui/react";  import React, { useState, useEffect } from 'react'  import './CSSheets.css'   function App() {     const [message, setMessage] = useState('');      useEffect(() => {         // setTimeout method to update the message          // after 3000 milliseconds or 3 seconds         const timeoutId = setTimeout(() => {             setMessage('Message delayed after 3 seconds!');         }, 3000);          // Clear the timeout after component unmounting         return () => clearTimeout(timeoutId);     }, []);       return (         <ChakraProvider>             <Box bg="lightgrey" w="100%" h="100%" p={4}>                 <h1 style={{ color: "green" }}>                     GeeksforGeeks                 </h1>                 <Text                     color="#2F8D46" fontSize="2rem"                     textAlign="center" fontWeight="400"                     my="1rem"                 >                     React hooks with animation                 </Text>                 <h2>Animated Gradient text </h2>                 <h1>{message}</h1>             </Box>         </ChakraProvider>     ); };   export default App 

Output:

Example 4: CSS transitions are a simple way to add animations to elements. In this example, CSS transition properties (like transition-property, transition-duration, transition-timing-function, and transition-delay) are defined in your CSS to smoothly animate changes.

CSS
/* Style.css */ div {     width: 400px;     height: 320px;     transition: width 2s ease-in .2s;     display: inline-block; }  div:hover {     width: 600px; } 
JavaScript
// App.js import {     ChakraProvider,     Text, Box, } from "@chakra-ui/react";  import React, { useState, useEffect } from 'react'  import './Style.css'  function App() {     const [count, setCount] = useState(0);      useEffect(() => {         setTimeout(() => {             setCount((count) => count + 1);         }, 1000);     });      return (         <ChakraProvider>             <Box bg="lightgrey" w="100%" h="100%" p={4}>                 <h1 style={{ color: "green" }}>                     GeeksforGeeks                 </h1>                 <Text                     color="#2F8D46" fontSize="2rem"                     textAlign="center" fontWeight="400"                     my="1rem"                 >                     React hooks with transition                 </Text>                 <h2><b>Transition Property </b></h2>                 <div>                     <p>transition-property: width</p>                     <p>transition-duration: 5s</p>                     <p>transition-timing-function: ease-in</p>                     <p>transition-delay: .2s</p>                     <p><b>We have rendered {count} times</b></p>                 </div>             </Box>         </ChakraProvider>     ); };  export default App 

Output:



Next Article
React MUI Transitions Util

G

geetanjali16
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

  • Page transition in React.js using Framer Motion
    Page transition in React JS while switching and page loading in Routing adds extra animation to the web app. Framer motion provides customizable and easy-to-use animations and gestures for a better appearance and transition effects. PrerequisitesReact JSreact-router-dombootstrapFramer-motionApproach
    5 min read
  • How to use Animation and Transition Effects in CSS ?
    With the help of CSS, you may design impressive visual effects for your website. Animation and transition effects are two common ways to add animation and visual effects to a web page. By attracting users' attention and directing them through your material, these effects may make your website more d
    4 min read
  • How to create card animation using React Transition Group ?
    Creating card animation using React Transition Group simply refers to displaying animations in the card when any DOM event occurs. React transition group provide simple and easy-to-use components to display animation in the React components. Prerequisites:React JSNPM and Node.jsReact JS Transition G
    3 min read
  • React MUI Transitions Util
    React MUI transition component enables you to define a change from one component state to another across time. Although it's most frequently used for animation component mounting and unmounting, it can also be utilized to depict in-place transition states. It's up to you to give those states purpose
    5 min read
  • React Chakra UI Other Transitions
    React Chakra UI has a Transition component which has types like Fade, ScaleFade, SlideFade, and Collapse. All these types provide animation effects and smooth transitions in the application. By using the transition types in the application, the appearance of the elements is enhanced and the applicat
    3 min read
  • Tailwind CSS Transitions and Animation Complete Reference
    Tailwind CSS is a highly customizable, low-level CSS framework that gives you all of the buildings blocks that you need. Tailwind CSS Transitions utilities control the transition and animation of elements. it provides transition classes like transition Property, duration, timing function, delay to m
    2 min read
  • Angular10 animation transition API
    In this article, we are going to see what is transition in Angular 10 and how to use it. The transition in Angular10 is used to create a transition for the animation in which an element will go from one state to another. Syntax: transition (stateChangeExpr, steps, options) NgModule: Module used by t
    2 min read
  • Difference between animation and transition in CSS
    CSS transitions allow you to change property values smoothly, but they always need to be triggered like hover. Property changes do not take effect immediately. Over a period of time, the property changes take place. For example, if you change the color of an element from white to black, the change o
    3 min read
  • Text Typing Animation Effect using HTML CSS and JavaScript
    To create a text-typing animation effect, we will use a combination of HTML structure, CSS animations, and JavaScript logic to create the typing and deleting text like effect. [GFGTABS] HTML <!-- index.html --> <html> <head> <link rel="stylesheet" href="styles.css
    2 min read
  • Responsive Number Counting Animation Using React JS
    In this article, we will create a responsive number counting animation using ReactJS. The application will show a number of statistics and each number will be animated as it goes up to the point value. Such a format of animation is often applied for interactive data within sites, for example, to dem
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences