MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  1. 2nd Month
  2. Week 6
  3. React JS
  4. Components Basics

React Function Components

PreviousWriting Markup with JSXNextProps vs State

Last updated 1 year ago

React Function Components are the equivalent of React Class Components but expressed as functions instead of classes. In the past, it wasn't possible to use state or side-effects in Function Components -- that's why they were called Functional Stateless Components -- but that's not the case anymore with which rebranded them to Function Components.

React Hooks bring state and side-effects to React Function Components. React comes with a variety of built-in hooks, but also the ability to create custom hooks for yourself or others. Let's see how the previous React Class Component can be used as a React Function Component:

const App = () => {  
    const [value, setValue] = React.useState('');  
    const onChange = event => setValue(event.target.value);  
    
    return (    
        <div>      
            <h1>Hello React Function Component!</h1>      
            <input value={value} type="text" onChange={onChange} />      
            <p>{value}</p>    
        </div>  
    );
};

The previous code only shows the Function Component with the input field. Since component state is needed to capture the state of the input field's value, we are using the built-in React useState Hook.

React Hooks were also introduced to bring side-effects to Function Components. In general, the built-in React useEffect Hook is used to execute a function every time props or state of the component are changed:

const App = () => {  
    const [value, setValue] = React.useState(    
        localStorage.getItem('myValueInLocalStorage') || '',  
    );  
    
    React.useEffect(() => {    
        localStorage.setItem('myValueInLocalStorage', value);  
    }, [value]);  
    
    const onChange = event => setValue(event.target.value);  
    
    return (    
        <div>      
            <h1>Hello React Function Component!</h1>      
            <input value={value} type="text" onChange={onChange} />      
            <p>{value}</p>    
        </div>  
    );
};

The previous code shows a useEffect hook which is executed every time the value of the input field from the state changes. When the function given as side-effect to the useEffect hook gets executed, it updates the local storage's value with the recent value from the state. Also the initial state for the Function Component with the useState hook is read from the local storage.

Last but not least, we can extract both hooks as one encapsulated Custom Hook which makes sure to synchronize the component state with the local storage. In the end, it returns the necessary value and setter function to be used in the Function Component:

const useStateWithLocalStorage = localStorageKey => {  
    const [value, setValue] = React.useState(    
        localStorage.getItem(localStorageKey) || '',  
    );  
    
    React.useEffect(() => {    
        localStorage.setItem(localStorageKey, value);  
    }, [value]);  
    
    return [value, setValue];
};

const App = () => {  
    const [value, setValue] = useStateWithLocalStorage(    
        'myValueInLocalStorage',  
    );  
    
    const onChange = event => setValue(event.target.value);  
    
    return (    
        <div>      
            <h1>Hello React Function Component!</h1>      
            <input value={value} type="text" onChange={onChange} />      
            <p>{value}</p>    
        </div>  
    );
};

Since it is extracted from the Function Component, it can be used for any other component to share reusable business logic. It is an abstraction and advanced pattern in React equivalent to Mixins, Higher-Order Components, and Render Prop Components. However, it may be worth to mention that React Function Components can be enhanced by React's Higher-Order Components and Render Prop Components as well.

React Function Components with Hooks and React Class Components are the status quo for writing modern React applications. However, I strongly believe that React Function Components with Hooks will replace React Class Components in the future. From there, React Class Components may be only seen in older React applications/tutorials again similar to React createClass Components and React Mixins. The same applies to Higher-Order Components and Render Prop Components, which may be replaced by React Hooks to share reusable logic.


All React Components share the common sense of how to use , because they are just used to pass information down the component tree. However, the usage of state and side-effects varies for React Class Components and React Function Components with lifecycle methods and hooks.

This guide has shown you all the different Types of React Components, how they are used, and how they are put into a historical context. All examples from the tutorial can be seen and tried out over . In the end it's perfectly fine to use React Class Components, Function Components with Hooks, advanced concepts like Higher-Order Components and React Render Prop Components. However, it's good to know for older React applications/tutorials that there were other React Components and Patterns used in the past as well.

2️⃣
React Hooks
React Props
here