0Pricing
React Native Academy · บทเรียน

Animated.Value และ Animated.View

สร้าง Animated.Value ควบคุมด้วย Animated.timing และเชื่อมเข้ากับพร็อพ style ของ Animated.View เพื่อทำให้ความทึบเคลื่อนไหวเมื่อเมาท์

Animated.Value และ Animated.View เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What Is the Animated API?

The Animated API is React Native's built-in library for creating smooth, performant animations. It works by tracking special animated values that can be driven by timing or physics engines and then connected to component style properties. Unlike CSS transitions on the web, React Native animations are expressed entirely in JavaScript but can be offloaded to native threads for performance.

The Animated API ships with every React Native installation — no extra packages needed. You import it directly from react-native.

import { Animated, View } from 'react-native';

Creating an Animated.Value

The core primitive is Animated.Value, which holds a numeric value that can change over time. You create one with new Animated.Value(initialValue) and store it in a ref so it persists across renders without triggering re-renders itself.

Using useRef is the recommended pattern because the animated value is mutable — you want the same object throughout the component's lifecycle. Initializing inside useState would create a new value on every render.

import React, { useRef } from 'react';
import { Animated } from 'react-native';

function MyComponent() {
  const opacity = useRef(new Animated.Value(0)).current;
  // opacity is an Animated.Value starting at 0
}

Animated.View: The Animated Container

Animated.View is a special version of View whose style prop can accept Animated.Value references. When the animated value changes, the view updates without going through the normal React reconciliation cycle, making it very efficient.

Animated equivalents exist for other core components too: Animated.Text, Animated.Image, and Animated.ScrollView. You can also create animated versions of custom components using Animated.createAnimatedComponent().

import { Animated, StyleSheet } from 'react-native';

function FadeBox({ opacity }) {
  return (
    <Animated.View style={[styles.box, { opacity }]}>
    </Animated.View>
  );
}

Driving Animation with Animated.timing

Animated.timing smoothly changes an Animated.Value from its current value to a target value over a specified duration. It accepts a config object with toValue, duration, and an optional easing function.

Calling .start() begins the animation. You can pass a callback to .start(callback) that fires when the animation completes, which is useful for chaining effects or updating state after an animation finishes.

import { Animated, Easing } from 'react-native';

Animated.timing(opacity, {
  toValue: 1,
  duration: 800,
  easing: Easing.ease,
  useNativeDriver: true,
}).start(() => {
  console.log('Fade in complete!');
});

Fade In on Mount Example

A classic use case is fading a component in when it first mounts. You initialize the opacity value at 0 and run a timing animation to 1 inside useEffect with an empty dependency array so it fires once after the component renders.

The component renders immediately (invisible at opacity 0) and then smoothly becomes visible over the animation duration. This technique prevents jarring content flashes on slow data loads.

import React, { useRef, useEffect } from 'react';
import { Animated, View, Text } from 'react-native';

export default function FadeIn() {
  const opacity = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(opacity, {
      toValue: 1,
      duration: 600,
      useNativeDriver: true,
    }).start();
  }, []);

  return (
    <Animated.View style={{ opacity }}>
      <Text>Hello World</Text>
    </Animated.View>
  );
}

Fade Out and Conditional Visibility

Animated opacity is also used to hide components. Fading to opacity 0 keeps the component in the layout (it occupies space) while making it invisible. To fully remove it after fading, update a state variable in the animation's completion callback.

This pattern is common for modals, toasts, and notifications that should animate out before being unmounted from the component tree.

const [visible, setVisible] = React.useState(true);

function fadeOut() {
  Animated.timing(opacity, {
    toValue: 0,
    duration: 400,
    useNativeDriver: true,
  }).start(() => setVisible(false));
}

return visible ? (
  <Animated.View style={{ opacity }}>
    <Text>I will fade away</Text>
  </Animated.View>
) : null;

Translating Position with translateX/Y

Beyond opacity, Animated.Value can drive position transforms like translateX and translateY. Transforms are applied in the transform style array. This lets you slide elements onto the screen from any direction.

Using transform instead of changing left or top is critical for performance because transforms do not trigger a layout pass — they are composited on the GPU, enabling 60fps animations even on lower-end devices.

const translateY = useRef(new Animated.Value(100)).current;

useEffect(() => {
  Animated.timing(translateY, {
    toValue: 0,
    duration: 500,
    useNativeDriver: true,
  }).start();
}, []);

return (
  <Animated.View style={{ transform: [{ translateY }] }}>
    <Text>Slides up from bottom</Text>
  </Animated.View>
);

Scaling Components with scale Transform

The scale transform grows or shrinks a component around its center point. Starting a component at scale: 0 and animating to 1 creates a pop-in effect, while animating from 1 to 0 creates a pop-out effect.

Scale animations feel natural for confirmation actions like a heart button in a social app or a checkmark appearing after a form submission. Combine scale with opacity for an even more polished result.

const scale = useRef(new Animated.Value(0)).current;

function popIn() {
  Animated.timing(scale, {
    toValue: 1,
    duration: 300,
    useNativeDriver: true,
  }).start();
}

return (
  <Animated.View style={{ transform: [{ scale }] }}>
    <Text>Pop in</Text>
  </Animated.View>
);

Interpolating Animated Values

Animated.Value.interpolate() maps the raw numeric value to a different output range. This is extremely useful when you want one animated value to drive multiple different style changes simultaneously.

For example, you can interpolate a single progress value from 0 to 1 into both a color string (going from red to green) and a pixel offset (going from 0 to 100). The inputRange and outputRange arrays define the mapping points.

const progress = useRef(new Animated.Value(0)).current;

const backgroundColor = progress.interpolate({
  inputRange: [0, 1],
  outputRange: ['#ff0000', '#00ff00'],
});

const translateX = progress.interpolate({
  inputRange: [0, 1],
  outputRange: [0, 200],
});

return (
  <Animated.View
    style={{
      backgroundColor,
      transform: [{ translateX }],
    }}
  />

Animating Border Radius and Colors

You can animate almost any numeric style property with Animated.Value, including borderRadius, width, height, and even colors when using interpolate. Animating a square to a circle by changing border radius creates fluid shape morphing effects.

Note that color animation requires useNativeDriver: false because color changes are not supported by the native driver. This means color animations run on the JS thread and are slightly less performant than transform animations.

const borderRadius = useRef(new Animated.Value(0)).current;

function morphToCircle() {
  Animated.timing(borderRadius, {
    toValue: 50,
    duration: 400,
    useNativeDriver: false, // layout props need JS driver
  }).start();
}

return (
  <Animated.View
    style={{
      width: 100,
      height: 100,
      backgroundColor: 'tomato',
      borderRadius,
    }}
  />

Looping Animations with Animated.loop

Animated.loop wraps another animation and repeats it indefinitely (or a set number of times with the iterations option). It is perfect for loading spinners, pulsing indicators, and continuous background effects.

To create a pulsing effect, animate opacity from 1 to 0.3 and back inside a loop. Always call .stop() on the loop animation when the component unmounts by returning it from the useEffect cleanup function to prevent memory leaks.

const pulse = useRef(new Animated.Value(1)).current;

useEffect(() => {
  const animation = Animated.loop(
    Animated.sequence([
      Animated.timing(pulse, { toValue: 0.3, duration: 800, useNativeDriver: true }),
      Animated.timing(pulse, { toValue: 1, duration: 800, useNativeDriver: true }),
    ])
  );
  animation.start();
  return () => animation.stop();
}, []);

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: Animated.Value holds a numeric value that can change over time, Animated.timing drives smooth transitions with a configurable duration and easing, and Animated.View accepts animated values in its style prop for opacity and transform animations. Next up we explore spring and decay physics-based animations.

คำถามที่พบบ่อย

บทเรียน “Animated.Value และ Animated.View” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “Animated.Value และ Animated.View” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “Animated.Value และ Animated.View”

สร้าง Animated.Value ควบคุมด้วย Animated.timing และเชื่อมเข้ากับพร็อพ style ของ Animated.View เพื่อทำให้ความทึบเคลื่อนไหวเมื่อเมาท์ คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “Animated.Value และ Animated.View” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. Animated.Value และ Animated.View
  2. แอนิเมชันแบบสปริงและการลดความเร็ว
  3. การทำหลายคุณสมบัติให้เคลื่อนไหวแบบขนานและแบบลำดับ
  4. ใช้ useNativeDriver สำหรับแอนิเมชัน 60fps
← กลับไปที่ React Native Academy