Week 1 - Counter App

2022-03-16

Welcome to Week 1 of React Curve

Hello developer! 👋 I'm excited to have you here.

React Curve is an open-source project where I share and create small UI components, illustrating concepts to build large-scale projects.

What is ReactJs?

React is a JavaScript library developed by Facebook in 2013 for building interactive User Interface (UI) components in web applications. Major companies like Facebook, Twitter, Uber, Netflix, Udemy, and many others use React in their development environments.

Why ReactJs?

Performance and Flexibility are core principles of ReactJs, coupled with a thriving community and a strong job market. ReactJs promotes composition and separates concerns, encouraging modular thinking. This concept, known as componentization, allows us to design small components before composing them into the entire page.

ReactJs provides a better way to compose user interfaces from reusable elements using JavaScript. It revolutionizes the way we think about interface composition, focusing on elements like buttons, lists, links, navigation, and more.

ReactJs leverages three key concepts: components, props, and state to create both simple and complex UI interfaces.


Counter App

counter app

This week, we've created a simple counter app in React. To create the counter component, we:

  • Created a state to hold the count
  • Started counting from 0
  • Implemented methods to increase and decrease the count
  • Updated the count on clicking the increase (+) and decrease (-) buttons

Code

Class Component

import React, { Component } from "react";

class Counter extends Component {
  state = {
    count: 0,
  };

  increment = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };

  decrement = () => {
    this.setState({
      count: this.state.count - 1,
    });
  };

  render() {
    return (
      <div className="counter">
        <button onClick={this.increment}>Increase + </button>
        <h2>{this.state.count}</h2>
        <button onClick={this.decrement}>Decrease - </button>
      </div>
    );
  }
}

export default Counter;

Function Component

import React, { useState } from "react";

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

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return (
    <div className="counter">
      <button onClick={increment}>Increase + </button>
      <h2>{count}</h2>
      <button onClick={decrement}>Decrease - </button>
    </div>
  );
}

export default Counter;

Disclaimer: This post reflects my personal experiences during this period. It doesn't claim to be the best or worst approach. Feel free to share your thoughts, better ways, or preferences in the discussion threads below!

Live Preview Source Code

Thanks for reading! 🚀