관리 메뉴

Silver Library (Archived)

OOP, but how with reactjs? 본문

F5. Library of Tools/React.js

OOP, but how with reactjs?

Ayin Kim 2023. 1. 11. 22:03
반응형

I already used number of features those provided by react.js, but I just noticed one thing. 

 

Have I followed OOP by the way?

What about design pattern?

 

Above all, how can I apply such OOP norm to any of them?

 

So, let me clarify.

OOP approach with classes are:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: 'Hello, World!' };
  }

  handleClick() {
    this.setState({ message: 'Hello, React!' });
  }

  render() {
    return (
      <div>
        <p>{this.state.message}</p>
        <button onClick={() => this.handleClick()}>
          Click me
        </button>
      </div>
    );
  }
}

In this example, MyComponent is a class that extends React.Component.

There is a constructorfunction that calls the parent class's constructor and sets an initial state for the component.

The render method is used to return the JSX, which will be rendered to the screen.

The component also has a handleClick method that updates the component's state when the button is clicked.

 

Wait, what about the usual instance? 

import { useState, useEffect } from 'react'

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

    useEffect(() => {
        console.log(`You clicked ${count} times`);
    }, [count])

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

In this case, MyComponent is functional component that uses useState hook to manage the componnet's state.

Then useEffect hook to perform a side effect, like updating the count when the button is clicked.