Friday, April 7, 2023

Functions vs Components in React, and useState

useState example:
import React, {useState} from 'react'

export default function Counter({initialCount}) {
    const [count, setCount] = useState(initialCount)
    return (
        <div>
            <button onClick = {() => setCount(prevCount => prevCount - 1)}>-</button>
            <span>{count}</span>
            <button onClick = {() => setCount(prevCount => prevCount + 1)}>+</button>
        </div>
    )
}


same thing using Component


import React, { Component } from 'react'

export default class Counter extends Component {

    constructor(props){
        super(props);
        this.state = {
            count: props.initialCount
        }
    }

    render() {
        return (
            <div>
                <button onClick={() => this.changeCount(-1)}>-</button>
                <span>{this.state.count}</span>
                <button onClick={() => this.changeCount(1)}>+</button>
            </div>
        )
    }

    changeCount(amount) {
        this.setState(prevState => {return { count: prevState.count + amount}})
    }

}



Popular VSCode Extensions for React

https://www.syncfusion.com/blogs/post/7-vs-code-extensions-for-react-developers.aspx