The Basics of React.js
Tags: webdev, javascript, react, frontend
Published: 2023-02-15 15:23:41

As a developer coming from regular HTML, CSS and Vanilla JS, it's important to understand that React is based on the concept of building reusable components that can be easily combined to create complex and interactive user interfaces. 

## What Is React.js

React is founded on the idea of creating reusable components that can be readily coupled to create complex and interactive user interfaces, which is crucial for beginners to understand. Declarative syntax is used by React, which makes the code simpler to comprehend and maintain.

React enables developers to write code that is more effective and performant, which is one of its main advantages. This is accomplished via a method known as "virtual DOM," in which the library updates only the portions of the user interface that require modification rather than the complete interface each time something changes.

## Advantages of React's Developer Community and Learning Resources
The enormous developer community and online materials made available by React are another advantage of adopting it. There are many tutorials, training programs, and resources available to help new React users get started.

React as a whole, is a strong library that may assist programmers in creating dynamic, responsive user interfaces for both online and mobile apps. To build high-quality applications, it's crucial for a newcomer to invest the time in learning the principles and best practices of React.

## Important Things To Note

When using React, a well-liked JavaScript toolkit for creating user interfaces, there are a few crucial things to understand. The following are some of the essential ideas and characteristics you need to be aware of:

**1. Components :**
React is built on the idea of components, which are modular pieces that may be reused to build user interfaces. Components can be either functional or class-based. They can render output based on input data they receive as "properties" from other components.

A simple code example of react components

```javascript
import React from 'react';

// A functional component that displays a greeting
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

// A class component that displays a counter
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ count: this.state.count + 1 });
  }

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

// A functional component that combines the two components
function App() {
  return (
    <div>
      <Greeting name="Alice" />
      <Counter />
    </div>
  );
}

export default App;

```
In this demo, we have three components:

1. Greeting: A functional component that takes a name prop and displays a greeting using that prop.
2. Counter: A class component that has a state object with a count property and a handleClick method that updates the count property when the button is clicked. The component displays the current count and a button that calls handleClick when clicked.
3. App: A functional component that combines the Greeting and Counter components.

**2. JSX:**
JSX is a syntax extension for JavaScript that lets in you to put in writing HTML-like code for your React components. JSX makes it smooth to create UI factors and additionally allows to hold the component`s logic and presentation collectively in a single place.

Here is a simple example

````javascript
import React from 'react';

function MyComponent() {
  const name = "John Doe";
  const age = 30;
  
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>You are {age} years old.</p>
    </div>
  );
}

export default MyComponent;
```


In this example, we define a functional component called `MyComponent`. Inside the component, we define two variables name and age. We then use JSX to render a div element with a h1 heading that displays a greeting using the name variable and a p element that displays the age variable. The curly braces {} are used to interpolate variables and expressions inside the JSX markup. Finally, we export the component so that it can be used in other parts of the application.


**3. State:**
State is an important concept in React that allows you to manage dynamic data in your application. A component's state is an object that can be updated and re-rendered as needed, based on user interactions or other events.

Here is a simple example of using state in React

````javascript

import React, { useState } from 'react';

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

  function handleIncrement() {
    setCount(count + 1);
  }

  function handleDecrement() {
    setCount(count - 1);
  }

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={handleIncrement}>+</button>
      <button onClick={handleDecrement}>-</button>
    </div>
  );
}

export default Counter;

```

In this example, we define a functional component called `Counter` that uses the `useState` hook to manage a state variable `count` initialized to 0. We also define two functions `handleIncrement` and `handleDecrement` that update the `count` state using the `setCount` function. Finally, we render a h1 heading that displays the current value of `count`, and two buttons that call the respective increment and decrement functions when clicked.

When the user clicks either button, the count state variable is updated and React automatically re-renders the component to reflect the new value.

**4. Props:** 
Props are short for properties and are used to pass data from one component to another. Props are read-only, which means that a child component cannot modify the props passed to it by its parent.

Here is a short example of props in react

````javascript

import React from 'react';

function Greeting(props) {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>You are {props.age} years old.</p>
    </div>
  );
}

export default Greeting;

```

In this example, we define a functional component called Greeting that receives two props: `name` and `age`. We use these props to render a h1 heading that displays a greeting using the name `prop`, and a `p` element that displays the age prop.

When we use this component in another part of our application, we can pass in values for the `name` and `age` props:


````javascript
import React from 'react';
import Greeting from './Greeting';

function App() {
  return (
    <div>
      <Greeting name="John" age={30} />
      <Greeting name="Jane" age={25} />
    </div>
  );
}

export default App;

```

In this example, we use the `Greeting` component twice, passing in different values for the `name` and `age` props each time. This will result in two different greetings being rendered on the page.

**5. React Router:** 
Router is a library that allows you to handle client-side routing in your React application. With React Router, you can define routes for your application and control the navigation between them.

Here is a simple example showing you how to use react router

````javascript
// React Router in React
import React from 'react';
import { BrowserRouter, Switch, Route, Link } from 'react-router-dom';

const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;
const Contact = () => <h1>Contact</h1>;

const App = () => (
  <BrowserRouter>
    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/contact">Contact</Link></li>
      </ul>
    </nav>

    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </Switch>
  </BrowserRouter>
);

export default App;

```

React Router is a library that provides declarative routing in a React application. It allows us to define routes and navigate between them using components like `BrowserRouter`, `Switch`, and `Route`. This makes it easy to build single-page applications with multiple views.


**6. Redux:** 
Redux is a state management library for React that provides a centralized store for managing application state. Redux can be useful for larger applications that require more complex state management.

Here is a simple example that shows you how redux works in react

````javascript
// Redux in React
import { createStore } from 'redux';

// Define the reducer function
const counterReducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

// Create a Redux store
const store = createStore(counterReducer);

// Dispatch actions to update the store
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });

// Access the current state of the store
console.log(store.getState());

```

Redux is a state management library that provides a predictable way to manage the state of a React application. It does this by maintaining a single source of truth called the store, which stores the state of the application. We can update the store by dispatching actions, which are simple objects that describe the changes we want to make to the state. We can also access the current state of the store using `store.getState()`


**7. Hooks:** 
Hooks are a newer feature in React that allow you to add state and other React features to functional components. Hooks provide a more concise and flexible way to manage state and lifecycle events in your components.

Here is a simple example explaining the concept of react hooks

````javascript
// Hooks in React
import React, { useState } from 'react';

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

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

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

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={handleIncrement}>+</button>
      <button onClick={handleDecrement}>-</button>
    </div>
  );
};

export default Counter;

```


**8. Context:**
Context is a feature in React that allows you to share data between components without the need to pass props down through multiple levels of the component tree.

Here is a short sample explaining context in react.

````javascript

// Context in React
import React, { createContext, useContext } from 'react';

// Create a context object
const UserContext = createContext();

// Define a component that provides the context value
const UserProvider = ({ children }) => {
  const user = { name: 'John', email: 'john@example.com' };
  return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};

// Define a component that consumes the context value
const UserInfo = () => {
  const user = useContext(UserContext);
  return (
    <div>
      <h1>User Info</h1>
      <p>Name: {user.name}</p>
      <p>Email: {user.email}</p>
    </div>
  );
};

// Render the app
const App = () => (
  <UserProvider>
    <UserInfo />
  </UserProvider>
);

export default App;

```

Context is a feature in React that allows data to be passed down the component tree without having to pass props down through every level of the tree. This can be useful when certain data needs to be accessed by many components in the tree. In this example, we create a context object using createContext, and then define a provider component that provides the context value to all child components using UserContext.Provider. We also define a consumer component that consumes the context value using the useContext hook. By wrapping the UserInfo component in the UserProvider, we can access the user object anywhere in the component tree without having to pass it down as a prop.


**9. Virtual Dom:**
 React uses a virtual DOM to efficiently update the UI based on changes in state or props. The virtual DOM is a lightweight representation of the actual DOM, and it allows React to avoid unnecessary re-renders and improve performance.

````javascript
// Virtual DOM in React
import React from 'react';
import ReactDOM from 'react-dom';

const App = () => (
  <div>
    <h1>Hello, world!</h1>
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));

```

In React, the Virtual DOM is an in-memory representation of the actual browser DOM. Instead of directly manipulating the browser DOM, React updates the Virtual DOM and then calculates the minimum number of changes needed to update the actual DOM. This makes React faster and more efficient than traditional DOM manipulation


## My Final Thoughts 

React is a JavaScript library for building dynamic user interfaces efficiently with its key feature being the use of a Virtual DOM. Developed and maintained by Facebook, it also provides a component-based architecture, JSX syntax, and a large community of developers, making it popular for web development.

These are just some of the important things to know in React. As you continue to work with the library, you will likely encounter other concepts and features that are useful for building great user interfaces.

_Feel free to leave a comment, I'll respond to it._