DEV Community

Silas
Silas

Posted on

Getting Started with ReactJS

Ever wanted to get started with react but just couldn't find the straight-to-the-point guide and you also couldn't handle sitting through hours of tutorials? Well, let's try it this way.

I will not even try to get you from 0-100 of react in this one post. Just a little push is what I promise, so let's dive right in.

What is React

React is a popular open-source javascript framework by Meta used primarily for building user interfaces majorly for single page applications.

Installation

To get started, you need to have node (and npm) installed. To install, follow the guide here

Once installation is complete, you can confirm by running node -v on your terminal(or command prompt), which should output something like v24.9.0. That should confirm the installation was successful.

Install React

Over the years, react installation has changed from the traditional create-react-app to more reliable and efficient methods of using scaffolds, specifically vite.

  • open your terminal(if not already opened)

  • Navigate to your desired directory

  • Run npm create vite@latest This will prompt you for a few inputs like project name, framework as shown:

terminal

  • Finally, execute the last 3 commands shown : cd project-name, npm install and finally npm run dev.

npm install installs the dependencies required by the project as defined in package.json
npm run dev starts the development server which runs your project locally.

And that's our checkpoint. You have successfully installed and ran a react project.

As of vite 8, the setup comes with:
/public - this directory contains public assets like images
/src - contains all the source code of the app
.gitignore - default populated .gitignore template
eslint.config.js - configuration for the linter
index.html - the main html file that react appends components
package*.json - stores configuration and dependencies for the app
README.md - basic vite documentation
vite.config.js - configuration for vite development server

Inside src, we have 2 css and 2 jsx files. The .jsx files are native to react, they denote react components.

App.css is styling used within App.jsx whereas
index.css is a global styling sheet for index.html, which App inherits.
Main.jsx is the entrypoint of the app. This is where the react app is injected into index.html's <div id="root"></div>

Now let's code ...

  • Delete everything in App.jsx and replace it with this:
function App(){
    return(<p>Hello React</p>)
}
Enter fullscreen mode Exit fullscreen mode

When you run the server , npm run dev and open the address http://localhost:5173 in browser, you should see Hello React displayed

Manage States with useState()

This is a snapshot of a component(and its data) at a particular point in time. Component's data changes over time, so each change represent a new state.
React has a state manager, useState() to manage change in states. When a state changes, react triggers a re-render of that component to show the change, e.g user typing into a textfield. Every keypress is a new state hence the textbox is re-rendered with the new data everytime.

To use this, first import useState at the top of the file:
import {useState} from 'react'

Within the function body:
const [count,setCount] = useState(0)

useState() takes a default value that represents the datatype of what the state stores.
Our example tells us that count is of type int

count -> state variable
setCount -> function to change state.

** NB: you should NEVER directly change count**

import { useState } from "react";

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

  function handleClick() {
    setCount((prev) => setCount(prev + 1));
  }

  return (
    <div>
      <p>Count: { count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This shows us a simple implementation of useState() in action.

TODO: Try implement a decrement.

UseEffect

This hook is used to define an action done when a particular event happens.
It is used to define what happens:

  • Immediately the app loads/runs
  • When a state changes.

The syntax for this is:

First, import: import { useEffect } from react
Second, implement:

useEffect(()=>{
//Some stuff to do only once everytime the component loads
})
Enter fullscreen mode Exit fullscreen mode


javascript
The one above will run only once when the component renders.

The one below will run only once on the initial render of the component.

useEffect(()=>{
//Some stuff to do once everytime the app loads
},[])
Enter fullscreen mode Exit fullscreen mode

The one below will run everytime the dependency changes. Dependency is a state variable

useEffect(()=>{
//Some stuff to do
},[dependency])
Enter fullscreen mode Exit fullscreen mode
import { useEffect, useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log("Run once everytime the component re-renders");
  });

  useEffect(() => {
    console.log("Run once everytime the app loads");
  }, []);

  useEffect(() => {
    console.log("Run  everytime count changes");
  }, [count]);

  function handleClick() {
    setCount((prev) => setCount(prev + 1));
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

TODO: Run this with the browser console open to see the output of the events.
The browser might display double outputs when you run. This happens because strictmode is enabled on react.

This guide has introduced you to useState and useEffect hooks in react.

Keep practicing, see you on the next one.

Top comments (0)