본문 바로가기
개념/React

React) local parameter - example 2

by kiseno 2025. 3. 18.
728x90
반응형
SMALL
import {useRef} from 'react';

const RefSample = () => {
    const id = useRef(1);
    const setID = (n) => {
        id.current = n;
    }
    const printId = () => {
        console.log(id.current);
    }
    return (
        <div>
            refSample
        </div>
    );
};

export default RefSample;

//Component가 랜더링되지 않는다.

### Component Breakdown

1. **Importing `useRef`**:
   ```jsx
   import {useRef} from 'react';
   ```
   - `useRef` is a React hook that is used to create a mutable reference object which remains consistent across re-renders.

2. **Using `useRef`**:
   ```jsx
   const id = useRef(1);
   ```
   - Here, `useRef` initializes a reference object `id` with a current property set to `1`. The `.current` property of the returned object is mutable and can be changed directly.

3. **Modifying the ref**:
   ```jsx
   const setID = (n) => {
       id.current = n;
   }
   ```
   - `setID` is a function that updates the `id.current` to a new value `n`. Unlike state updates, changing a ref does not trigger a component re-render.

4. **Accessing the ref**:
   ```jsx
   const printId = () => {
       console.log(id.current);
   }
   ```
   - `printId` is a function designed to log the current value of `id.current` to the console. This demonstrates how refs can be used to store and retrieve values across re-renders without causing visual updates to the component.

5. **Render Method**:
   ```jsx
   return (
       <div>
           refSample
       </div>
   );
   ```
   - The render function simply returns a `div` with the text "refSample". There are no user interactions or visible indicators of the `id` ref's value within the rendered output.

### Discussion

This example clearly shows how `useRef` can be used to maintain a mutable value across re-renders without causing the component to update its output. However, the example could be enhanced to include interactive elements that demonstrate the ref being updated and accessed:

### Enhanced Example with Interaction

```jsx
import { useRef } from 'react';

const EnhancedRefSample = () => {
    const id = useRef(1);

    const setID = (n) => {
        id.current = n;
    }

    const printId = () => {
        console.log(id.current);
    }

    return (
        <div>
            <div>Enhanced refSample</div>
            <button onClick={() => setID(5)}>Set ID to 5</button>
            <button onClick={printId}>Print ID</button>
        </div>
    );
};

export default EnhancedRefSample;
```

In this enhanced version:
- Added two buttons: one to change the `id` ref to a new value (`5`) and another to print the current value of the `id` ref to the console.
- These additions allow users to interact with the component and observe the behavior of `useRef` in managing values across re-renders.

### Conclusion

The original `RefSample` component is a straightforward demonstration of `useRef`. By enhancing it with buttons for interaction, it becomes more evident how `useRef` can be practically utilized in applications for storing and manipulating values that don't directly affect the rendered output, akin to instance variables in class components. This approach is useful in scenarios where you need to track values without re-rendering the component, such as managing focus, timers, or other persistent values.

728x90
반응형
LIST

'개념 > React' 카테고리의 다른 글

React) custom Hook - useInputs  (0) 2025.03.20
React) local parameter - example 1  (0) 2025.03.19
React) useReducer - counter  (0) 2025.03.17
React) useReducer - info  (0) 2025.03.16
React) React 초기 세팅  (0) 2025.03.15