FRONTEND

React Topics

로그앤 2023. 6. 25. 01:57

1. Components and Props

Controlled Components

Controlled components are React components whose form elements (such as input fields) are controlled by React state. This means that the component's state holds the current value of the form element, and any changes to the value are handled by updating the state. Here's an example:

import React, { useState } from 'react';

function ControlledComponent() {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <input type="text" value={value} onChange={handleChange} />
  );
}

In the above example, the value state variable holds the current value of the input field. The handleChange function updates the state with the new value whenever the input changes. The value prop of the input element is set to the value state variable, making it a controlled component.

 

Multiple Components 

In React, you can create multiple components and compose them together to build complex user interfaces. 

import React from 'react';

function Header() {
  return <h1>Welcome to My App</h1>;
}

function Content() {
  return <p>This is the content of the app.</p>;
}

function App() {
  return (
    <div>
      <Header />
      <Content />
    </div>
  );
}

In this example, the Header and Content components are defined separately and then used within the App component. 

This allows for reusability and modularity in building the UI.

 

Component Lifecycle 

In React, components have a lifecycle that includes various phases like mounting, updating, and unmounting. 

You can use lifecycle methods to perform actions at specific points in the component's lifecycle. 

However, with the introduction of React Hooks, the traditional lifecycle methods are not commonly used anymore. 

Hooks provide a more flexible and modern way of managing component state and lifecycle. 

Here's an example using the useEffect hook:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // This function will be called when the component mounts
    console.log('Component mounted');

    return () => {
      // This function will be called when the component unmounts
      console.log('Component unmounted');
    };
  }, []); // Empty dependency array means it runs only on mount and unmount

  useEffect(() => {
    // This function will be called whenever the 'data' prop changes
    console.log('Data prop changed');
  }, [data]);

  return <div>My Component</div>;
}

In this example, the useEffect hook is used to perform actions based on the component's lifecycle. 

The first useEffect is called when the component mounts and unmounts, 

while the second useEffect is called whenever the data prop changes. 

The cleanup function returned by the hook is used to clean up 

any resources or subscriptions when the component unmounts.

Routing With Params

Routing in React allows you to render different components based on the current URL. 

Params in routing refer to 

dynamic segments in the URL path that can be used to pass information to components. 

Here's an example using the React Router library:

import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link, useParams } from 'react-router-dom';

function Home() {
  return <h1>Welcome to the Home page!</h1>;
}

function User() {
  const { userId } = useParams();

  return <h1>Hello, User {userId}!</h1>;
}

function App() {
  return (
    <Router>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/users/1">User 1</Link>
          </li>
          <li>
            <Link to="/users/2">User 2</Link>
          </li>
        </ul>
      </nav>

      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/users/:userId" component={User} />
      </Switch>
    </Router>
  );
}

In this example, the React Router library is used to handle routing. The Link component is used to create navigation links. The Switch component renders only the first Route that matches the current URL.

The User component extracts the userId param from the URL using the useParams hook.

So when you click on the "User 1" or "User 2" links, the User component will render with the corresponding user ID. 

Use APIs

Fetching data from APIs is a common task in React applications. 

You can use the fetch function or libraries like Axios to make HTTP requests and retrieve data. 

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

function DataFetching() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const jsonData = await response.json();
        setData(jsonData);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

In this example, the DataFetching component fetches data from an API using the fetch function inside the useEffect hook.The fetched data is stored in the data state variable,

and the loading and error states are used to handle the loading and error states of the request.

The component renders different UI based on the current loading and error states. 

Basic Hooks

useState The useState hook is used to add state to functional components in React.

It returns an array with two elements: the current state value and a function to update the state. Here's an example:

import React, { useState } from 'react';

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

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

In this example, the count state variable is initialized with a value of 0 using useState. 

The increment and decrement functions update the count state variable when the corresponding buttons are clicked. 

useEffect 

The useEffect hook is used to perform side effects in functional components. 

It takes a function as its first argument, which will be executed after the component renders. Here's an example:

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

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((prevSeconds) => prevSeconds + 1);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, []);

  return <div>Seconds: {seconds}</div>;
}

Controlled and Uncontrolled Components 

Controlled components, as mentioned earlier, are form elements whose value is controlled by React state. 

In contrast, uncontrolled components allow form elements to manage their own state internally. 

Here's an example of an uncontrolled input component:

import React, { useRef } from 'react';

function UncontrolledComponent() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    const value = inputRef.current.value;
    console.log('Input value:', value);
    // Perform further actions with the value
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, the inputRef is used to reference the input element. 

When the form is submitted, the value of the input element can be accessed directly using inputRef.current.value. 

The value is not controlled by React state, so you can access it without explicitly updating the state.