React Course: Creating a Counter App Example

In modern web development, React is one of the most popular libraries. Using React makes it easier to build user interfaces, and thanks to its component-based structure, code reusability and management are convenient. In this tutorial, we will create a basic counter app and explore the fundamental concepts of React and how to implement a real UI.

1. Introduction to React

React is an open-source JavaScript library developed by Facebook, optimized for building and managing UI components. By using React, you can develop each component independently and dynamically update the UI through state changes. This allows for efficient work even in complex SPAs (Single Page Applications).

2. Overview of the Counter App

The counter app is one of the simplest forms of an application that allows users to increase or decrease a number by clicking a button. Through this example, you will learn the basic concepts of React such as components, state, and event handling.

3. Setting Up the Development Environment

To get started with React development, you need to have Node.js and npm installed on your PC. Node.js is a JavaScript runtime environment, and npm is a JavaScript package manager.

  • Install Node.js: Download and install the LTS version from the official Node.js website.
  • Install create-react-app: create-react-app is a tool that makes it easy to create React applications. Enter the following command in the command window to install it.
npm install -g create-react-app

4. Creating a New React Project

Now, let’s create a new project using create-react-app. Enter the following command to create a project named ‘counter-app’:

npx create-react-app counter-app

Once the project is successfully created, we will navigate to the directory and run the app.

cd counter-app
npm start

By accessing http://localhost:3000 in your browser, you can check the default React app screen.

5. Implementing the Counter Component

Now, let’s create the component that will implement the counter functionality. Create a file named Counter.js in the src folder and write the code as follows:

import React, { useState } from 'react';

const Counter = () => {
    const [count, setCount] = useState(0);

    const increment = () => {
        setCount(count + 1);
    };

    const decrement = () => {
        setCount(count - 1);
    };

    return (
        

Counter: {count}

); }; export default Counter;

6. Adding the Counter Component to App.js

Now, we will add the newly created Counter component to the src/App.js file to display it on the screen. The code is as follows:

import React from 'react';
import './App.css';
import Counter from './Counter';

function App() {
    return (
        
); } export default App;

7. Applying Styles

To make the UI of the counter app look better, let’s add some CSS. Add the following styles to the src/App.css file:

.App {
    text-align: center;
}

.App-header {
    background-color: #282c34;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: calc(10px + 2vmin);
    color: white;
}

button {
    margin: 10px;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}

8. Running the Counter App

Everything is ready, so let’s run the app again using the npm start command. You will be able to see the counter increasing and decreasing in the browser.

9. Implementing Additional Features

Let’s add more features to the counter app to gain a deeper understanding of React.

  • Reset Function: Add a button to reset the counter to 0.
  • Even/Odd Distinction: Change the background color based on whether the counter value is even or odd.

Adding the Reset Function

Let’s add a reset button. Modify the Counter.js file as follows:

const reset = () => {
    setCount(0);
};

Then, add the reset button below it.

<button onClick={reset}>Reset</button>

Even/Odd Distinction

Let’s implement changing the background color based on whether the counter value is even or odd. Modify the Counter.js file as follows:

const backgroundColor = count % 2 === 0 ? 'lightblue' : 'lightcoral';

return (
    <div style={{ backgroundColor }}>
        <h1>Counter: {count}</h1>
        <button onClick={increment}>Increase</button>
        <button onClick={decrement}>Decrease</button>
        <button onClick={reset}>Reset</button>
    </div>
);

10. Conclusion

Through this tutorial, we covered the basic concepts of React while implementing a counter app. React is a wonderful tool that helps build more complex applications based on these basic components. I hope this tutorial has been a valuable learning experience for you. I recommend using React to create various projects in the future.

11. References

This article was written as part of a React tutorial.

React Course: Optimization and Memorization

React is a very popular JavaScript library for building UI. Managing complex applications while using React is not an easy task. In this process, performance optimization and memoization play an important role. This course will explain various techniques and concepts to improve the performance of React applications.

1. Basic Concepts of React

React has a component-based architecture, where each component independently manages its state and renders the UI. React focuses on improving performance by minimizing actual DOM changes through the Virtual DOM. However, not all components operate efficiently by default, and optimization is necessary.

2. The Need for Performance Optimization

In complex applications, unnecessary rendering or prolonged data processing can occur. These issues can degrade the user experience, and if optimization is not applied, the application will perform slowly. Therefore, performance optimization becomes an essential part of application development.

2.1. Goals of Optimization

  • Improvement of rendering speed
  • Increased efficiency in state management
  • Minimization of unnecessary calculations

3. Memoization in React

Memoization is an optimization technique that stores the results of function calls to avoid redundant calculations for the same input values. Utilizing memoization in React can improve rendering performance. In React, memoization is primarily implemented using React.memo, useMemo, and useCallback hooks.

3.1. React.memo

React.memo memoizes a component, preventing re-rendering when the same props are passed. For instance, when a child component does not depend on the parent’s state, using React.memo can reduce unnecessary rendering.

const MyComponent = React.memo(({ value }) => {
    console.log("Rendering: ", value);
    return <div>{value}</div>;
});

3.2. useMemo

The useMemo hook memoizes the calculation results within a component, preventing repeated calculations as long as the values specified in the dependency array do not change. This allows for the optimization of complex calculations.

const memoizedValue = useMemo(() => {
    return computeExpensiveValue(a, b);
}, [a, b]);

3.3. useCallback

The useCallback hook memoizes a function, reusing the previously created function unless the values specified in the dependency array change. This helps to prevent unnecessary rendering in child components.

const memoizedCallback = useCallback(() => {
    doSomething(a, b);
}, [a, b]);

4. Additional Tips for React Optimization

  • Proper State Management: Depending on the scale of your project, it’s advisable to use state management libraries like Context API, Recoil, or Redux.
  • Maintain Immutability: By preserving the immutability of state, you can maximize React’s optimization capabilities.
  • Lazy Loading: Load components or resources only when needed to reduce initial rendering time.

5. Practice: Applying Memoization

After understanding the optimization techniques, let’s apply memoization to a React application. Here is an example that demonstrates improved performance through memoization.

import React, { useState, useMemo } from 'react';

const ExpensiveComponent = ({ calculate }) => {
    const result = useMemo(() => {
        return calculate();
    }, [calculate]);

    return <div>Result: {result}</div>;
};

const App = () => {
    const [count, setCount] = useState(0);

    const calculate = () => {
        let total = 0;
        for (let i = 0; i < 1e6; i++) {
            total += i;
        }
        return total + count;
    }

    return (
        <div>
            <button onClick={() => setCount(count + 1)}>Increase Count</button>
            <ExpensiveComponent calculate={calculate} />
        </div>
    );
};

export default App;

6. Conclusion

Optimization and memoization in React applications are important factors in providing efficient performance. By utilizing React.memo, useMemo, and useCallback, you can reduce unnecessary rendering and calculations, thereby enhancing the user experience. Apply the concepts you’ve learned from this course to achieve performance optimization in your projects.

React Course: First Encounter with JavaScript

Hello! In this course, we will delve deeply into React and JavaScript. The React we will use is a component-based library that is very useful for building user interfaces (UI). At the same time, JavaScript is a language that is essential for understanding and utilizing React. We will start with the basic concepts of JavaScript for those who are new to it.

1. Understanding JavaScript

JavaScript is the most widely used programming language in web development. It has become one of the core technologies of the web, alongside HTML and CSS. With JavaScript, we can add dynamic features to web pages and allow for interaction with users.

1.1 History of JavaScript

JavaScript was first developed by Brendan Eich in 1995. Initially, it was used for writing simple scripts within browsers, but over time it began to be used for developing complex applications as well.

1.2 Basic Syntax of JavaScript

  • Variable Declaration: To declare a variable, we use var, let, and const. let and const have block scope, and const declares a constant that cannot be reassigned.
  • Data Types: JavaScript supports various data types. The main data types are as follows:
    • Number
    • String
    • Boolean
    • Object
    • Array
    • Null
    • Undefined
  • Function: To define a function, we write as follows:
    function sayHello(name) {
        return "Hello, " + name + "!";
    }

2. Understanding React

React is a JavaScript library developed by Facebook, which is very useful for building user interfaces. React allows us to manage the UI by breaking it down into independent pieces (components) using a component-based structure.

2.1 Features of React

  • Component-Based: The UI of the application can be divided into multiple independent components, making it easier to manage.
  • Virtual DOM: React uses a virtual DOM to minimize changes to the actual DOM and optimize performance.
  • One-Way Data Binding: Data flows from parent components to child components, which makes the flow of data clear.

2.2 Installing and Setting Up React

To use React, you need to install Node.js and npm (Node Package Manager). After installation, you can create a new React project using the following command:

npx create-react-app my-app

Now, navigate to the project directory:

cd my-app

3. Creating Your First React Component

Now let’s create a React component. Basic React components are defined as JavaScript functions or classes. Here is an example of creating a functional component:

import React from 'react';

function HelloWorld() {
    return 

Hello, React!

; } export default HelloWorld;

In the code above, we define a component called HelloWorld, which displays the phrase “Hello, React!” on the screen.

3.1 Using Components

To use the created component in another file, you can import it and use it as a JSX tag. For example:

import HelloWorld from './HelloWorld';

function App() {
    return (
        
); } export default App;

4. Understanding JSX

In React, we use JSX (JavaScript XML) to define the UI. JSX is a syntax that allows you to write HTML within JavaScript code. Using JSX makes the code more readable.

4.1 JSX Syntax

  • JSX is similar to HTML, but you must use className instead of class.
  • You can insert JavaScript expressions into tags using curly braces ({}).
  • To return multiple JSX elements, they must be wrapped in a single parent element.

5. State Management and Lifecycle

In React, you can manage the state of a component and control the creation and destruction of a component through lifecycle methods.

5.1 State Management

import React, { useState } from 'react';

function Counter() {
    const [count, setCount] = useState(0);

    return (
        

Current Count: {count}

); } export default Counter;

In the example above, we are managing the component’s state using the useState hook. The count increases each time the button is clicked.

5.2 Lifecycle Methods

Lifecycle methods are methods called during the creation, updating, and destruction of a component. In class components, you can use the following lifecycle methods:

class MyComponent extends React.Component {
    componentDidMount() {
        console.log('The component has been mounted.');
    }

    componentDidUpdate() {
        console.log('The component has been updated.');
    }

    componentWillUnmount() {
        console.log('The component will unmount.');
    }

    render() {
        return 

React Lifecycle

; } }

6. Event Handling

In React, handling HTML events is very straightforward. When handling events, you use properties like onClick or onChange.

function App() {
    const handleClick = () => {
        alert('The button has been clicked!');
    };

    return ;
}

7. Using External APIs

Let’s learn how to communicate with external APIs using React. For example, using fetch() to retrieve data.

import React, { useState, useEffect } from 'react';

function DataFetching() {
    const [data, setData] = useState([]);

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            .then(data => setData(data));
    }, []);

    return (
        
    {data.map(post => (
  • {post.title}
  • ))}
); } export default DataFetching;

8. Conclusion

In this course, we explored the basic concepts of React and JavaScript in depth. React is one of the most important technologies in modern web development. In the future, you will learn more about how to utilize and optimize it. I hope the journey to learn React will be helpful for you!

References

React Course: Conditional Statements

React is a JavaScript library for building user interfaces. One of the most common things you’ll encounter while using React is conditional statements. In this tutorial, we will explore various ways and techniques to use conditional statements in React. Understanding and effectively using conditional statements is an essential element of React development.

1. What is a conditional statement?

A conditional statement is a syntax that controls the flow of a program based on whether a specific condition is true or false. The most commonly used conditional statements in JavaScript are the if, else, and else if statements.

2. Using conditional statements in React

There are many situations where you need to use conditional statements in React. For example, you can modify how components are rendered based on specific conditions or display different content to the user. Here are some ways to use conditional statements in React:

2.1. Conditional rendering using if statements

The simplest method is usually to use JavaScript’s if statements. You can return different JSX based on conditions. Here’s an example code:

const Greeting = ({ isLoggedIn }) => {
  if (isLoggedIn) {
    return <h1>Welcome!</h1>;
  } else {
    return <h1>Please log in.</h1>;
  }
};

The above code renders different messages based on the value of the isLoggedIn prop.

2.2. Conditional rendering using the ternary operator

Using the ternary operator ?: allows for more concise code for conditional rendering. For example:

const Greeting = ({ isLoggedIn }) => {
  return (
    <h1>{isLoggedIn ? 'Welcome!' : 'Please log in.'}</h1>
  );
};

This kind of syntax makes the code shorter and easier to understand.

2.3. Conditional rendering using the logical && operator

In React, you can use the && operator to render a specific component only when the condition is true. Consider the following example:

const Greeting = ({ isLoggedIn }) => {
  return (
    <div>
      {isLoggedIn && <h1>Welcome!</h1>}
    </div>
  );
};

The above code displays the message “Welcome!” only if isLoggedIn is true.

3. Controlling components using conditional rendering

Conditional statements in React can be used to control the rendering of various components beyond just displaying messages. Here’s a more advanced example of conditional rendering:

const UserProfile = ({ user }) => {
  return (
    <div>
      {user ? (
        <div>
          <h1>Profile of {user.name}</h1>
          <p>{user.email}</p>
        </div>
      ) : (
        <h1>Unable to provide user information.</h1>
      )}
    </div>
  );
};

The above code shows the profile information when there is user data, and displays an error message otherwise.

4. Using conditional statements in business logic

In React, conditional statements can be utilized not only for the UI but also for business logic. You can use conditional statements within component state or event handlers to perform specific actions. For example:

const App = () => {
  const [count, setCount] = React.useState(0);

  const increaseCount = () => {
    if (count < 10) {
      setCount(count + 1);
    }
  };

  return (
    <div>
      <button onClick={increaseCount}>Count: {count}</button>
    </div>
  );
};

The above code increases the count every time the user clicks the button, but limits the increase to a maximum of 10.

5. Conclusion

Using conditional statements in React is an essential skill. Conditional rendering helps create complex user interfaces and improves user experience. If you have learned how to correctly use conditional statements in React through this tutorial, you will be able to create more efficient and dynamic applications.

I hope this will be very helpful for your future React development. If you have any additional questions or comments, please leave them in the comments!

React Tutorial: Data Types

React is a JavaScript library for building user interfaces that allows you to create reusable UI elements through a component-based architecture. In this tutorial, we will dive deeper into data types in React. A data type defines the format in which data is stored and is the first consideration when declaring variables in JavaScript. Understanding data types is a crucial foundation for effectively using React and developing complex applications.

1. Introduction to JavaScript Data Types

JavaScript is a dynamically typed language, which means that the type of a variable is determined at runtime. JavaScript provides seven basic data types:

  • Undefined: Represents a value that is not defined, which occurs when a variable has been declared but not assigned a value.
  • Null: A data type that intentionally represents ‘no value’. Null is primarily used for the initialization of objects.
  • Boolean: A data type that can only have two values, true or false, and is very commonly used in conditional statements.
  • Number: Includes both integers and floating-point numbers. JavaScript treats all numbers as 64-bit floating-point format.
  • String: A collection of characters used for processing strings. It can be enclosed in single quotes (‘) or double quotes (“).
  • Symbol: A data type introduced in ES6, representing unique and immutable values. It is primarily used as property keys for objects.
  • Object: A composite data type that can have various properties and methods. All objects, including Array, Function, Date, etc., are included in this type.

2. Using Data Types in React

In React, data types play an important role in defining the state and props of components. Proper management of state and props can enhance the overall stability and performance of the application.

2.1 Props

Props are the means by which data and methods are passed to components. Each component operates based on the information passed down from its parent component through its props. Let’s look at an example of how to use props:


function Greeting(props) {
    return <h1>Hello, {props.name}!</h1>;
}

function App() {
    return <Greeting name="React User"/>;
}
    

2.2 State

State is a way for components to manage data dynamically. State can only be accessed and modified within the component, and when the state changes, React re-renders that component. Let’s see how to use state in the following example:


import React, { useState } from 'react';

function Counter() {
    const [count, setCount] = useState(0);
    
    return (
        <div>
            <p>Current Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increase Count</button>
        </div>
    );
}
    

3. Data Type Validation

In React, we commonly use PropTypes to validate the data types of props. It allows us to verify whether the props passed to a component match the expected data types, which helps reduce bugs. Here is an example of how to use PropTypes:


import PropTypes from 'prop-types';

function Greeting({ name }) {
    return <h1>Hello, {name}!</h1>;
}

Greeting.propTypes = {
    name: PropTypes.string.isRequired,
};
    

4. Arrays and Objects

In React, arrays and objects are essential data types for structuring data. Arrays are collective data structures that can be manipulated using methods like map() and filter(). Objects consist of key-value pairs and are useful for encapsulating multiple data items.

4.1 Using Arrays

A common example is how to render a list:


const fruits = ['Apple', 'Banana', 'Orange'];

function FruitList() {
    return (
        <ul>
            {fruits.map((fruit, index) => <li key={index}>{fruit}</li>)}
        </ul>
    );
}
    

4.2 Using Objects

When using objects, you can access data in the following way:


const user = {
    name: 'Hong Gil-dong',
    age: 30,
};

function UserInfo() {
    return <p>Name: {user.name}, Age: {user.age}</p>;
}
    

5. Advanced Data Types and React

In React, advanced data types can be used for managing state. For example, you can manage complex states by combining various data types through conditionals or switch statements.

5.1 Advanced State Management

Using the useReducer hook allows for complex state management. Here is an example of using useReducer:


import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return { count: state.count + 1 };
        case 'decrement':
            return { count: state.count - 1 };
        default:
            throw new Error();
    }
}

function Counter() {
    const [state, dispatch] = useReducer(reducer, initialState);
    
    return (
        <div>
            <p>Current Count: {state.count}</p>
            <button onClick={() => dispatch({ type: 'increment' })}>Increase Count</button>
            <button onClick={() => dispatch({ type: 'decrement' })}>Decrease Count</button>
        </div>
    );
}
    

Conclusion

In this tutorial, we covered the key concepts of data types in React, the use of props and state, data type validation, and methods for managing complex states. A deep understanding of data types greatly aids in optimizing the performance of React applications and reducing bugs. I hope you experience their importance in the React applications you create in the future.

References