Getting Started with React Hooks - An Overview

Getting Started with React Hooks - An Overview
- 4th Mar, 2020 | 6min read

React is one of the most popular JavaScript library for building user interfaces, widely used to build single page applications and is a open-source project created by Facebook

Earlier we use class and react component but from and after version 16.8 it moves to the functional programming called as Hooks which is more easy to understand and code

Current version supports class and react component with 100% backwards-compatible, so not to worry

And it's recommended to all coders to use hooks who are new to React now

Prerequisites

Must have installed Node.js and npm
Before we proceed, you must have some basic knowledge of

  • HTML & CSS.
  • JavaScript (ES6 syntax and features) and programming concepts.

Goals

  • Learn what is React and its basic concepts.
  • Learn what is JSX, which is used by React.
  • Build a very simple React app that demonstrates the basic concepts.

What is React?

  • React is the most used popular JavaScript library.
  • React is used to build user interfaces (UI) on the front end.
  • React is the view layer of an MVC application (Model View Controller)
  • React is using JSX (JavaScript + XML), and is optional but recommended

One of the most important aspects of React is the fact that you can create custom components, which are like reusable HTML elements, to quickly and efficiently build user interfaces. And the best part, easy to maintain

What is JSX: JavaScript + XML ?

JSK stands for JavaScript XML which is similar to HTML, but it's not quite HTML.

With JSX, we can write what looks like HTML, and also we can create and use our own custom tags. Here's what JSX looks like assigned to a variable.

JSX
const jsx = <h1 className="title">Hello, React!</h1>

Using JSX is not mandatory for writing React but is recommended. Under the hood, it's running createElement, which takes the tag, object containing the properties, and children of the component and renders the same information. The below code will have the same output as the JSX above.

No JSX
const noJsx = React.createElement('h1', { className: 'title' }, 'Hello, React!')

JSX is actually closer to JavaScript, not HTML, so there are a few key differences to note when writing it.

  • className is used instead of class for adding CSS classes, as class is a reserved keyword in JavaScript.
  • Properties and methods in JSX are camelCase - onclick will become onClick.
  • Self-closing tags must end in a slash - e.g. <img /> <input />

We can embed JavaScript expressions inside JSX using curly braces { }, including variables, functions, properties, and comments.

const name = 'Rahul'
const jsx = <h1>Hello, {name}</h1>

JSX is easier to write and understand than creating and appending many elements in JavaScript, and is one of the reasons people love React so much.

So, let's create a basic React App to understand it batter

Create React App

Avoiding all difficulties, Facebook has created Create React App, an environment that comes pre-configured with everything you need to build a React app.

To set up create-react-app, run the following code in your terminal. Make sure you have installed Node.js.

npx create-react-app react-hook-app
Creating a new React app in F:\MyReactApp\react-hook-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Once that finishes installing, move to the newly created directory and start the project.

cd react-hook-app
npm start

Once you run this command, a new window will pop-up at localhost:3000 with your newly created React app.

react hook app

If you look into the project structure folder (In this case react-hook-app),

react-hook-app
    ── node_modules
    ── public
    ── src
    ── .gitignore
    ── package-lock.json
    ── package.json
    ── package.json
    ── README.md    

/node_modules - Contains all the dependency modules to run the project
/public - To store the static files of the project
/src - Contains all our React Codes
.gitignore - Contains file and folder names to avoid while uploading the project on github repository,
package-lock.json - Contains the metadata about all the dependency modules your app is using now
package.json - Contains the information about the project and the dependency modules used in it
README.md - Contains the basic information about the project

Let's check the Hot-Reload which automatically compiles on saving any updates/changes in our React code, Edit the line in /src/App.js within return( ) like :

return (
  <h1>Edited and saved to hot-reload!</h1>
  ....
);

And replace it with any other text. Once you save the file, you'll notice localhost:3000 compiles and refreshes with the new data.

Go ahead, just keep index.css and index.js and delete all other files out of the /src directory.

Now we create a fresh app.css and app.js, a fresh new custom component for your better understanding

src/app.css
.myapp {
  border : 5px solid deeppink;
  padding : 5px 10px;
  margin:10px;
}

.myapp p {
  color: blue;
}

Now in app.js, we're importing React and app.css file.

src/app.js
import React from 'react'
import './app.css'

Let's create our App component. Now I'm adding a div element with a class. You'll notice that we use className instead of class. This is because react is using JSX (JavaScript + XML), and is not HTML.

Remember! Every component name must starts with Uppercase to avoid errors

src/app.js
// Creating 'App' component
function App() {
  // Your component logics if any
  const today = new Date().toString();

  //Final output to be returned, the JSX
  return (
    <div className="myapp">      <h1>Hello, React!</h1>      <p>Today is : {today}</p>   {/* Accessing variable within { } */}    </div>  )
}
//Exporting component for reusability
export default App;

Here's our full app.js.

src/app.js
import React from 'react'
import './app.css'

function App() { 
  const today = new Date().toString();
    return (
      <div className="myapp">
        <h1>Hello, React!</h1>
        <p>Today is : {today}</p>
      </div>
    )
}

export default App;

Finally, we'll import our App component and render the App to the root. Just clear old one and replace it with the below code

src/index.js
import React from 'react'
import ReactDOM from 'react-dom';
import './index.css'
import App from 'app'

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

If you go back to localhost:3000, you'll see "Hello, React!" and current date written in blue color, all within a deeppink colored box.

Now we have all set to actually begin working with React.

Conclusion

In this article we have learned what is React and JSX, how to create a basic react app and run it.

NewOld