Building an App with firebase and react hooks in simple way
Tags: react, javascript, webdev, tutorial
Published: 2020-02-22 18:01:49

---
title: Building an App with firebase and react hooks in simple way
published: true
description: Building an App with firebase and react hooks in simple way
tags: react,javascript,webdev,tutorial
canonical_url: https://cloudnweb.dev/2020/02/building-an-app-with-firebase-and-react-hooks-in-simple-way/

---
<!-- wp:image {"align":"center","id":2250,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://cloudnweb.dev/wp-content/uploads/2020/02/React-Hooks.png" alt="firebase and reack hooks" class="wp-image-2250"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>This article is going to be a complete tutorial about Building a Note application with firebase and react hooks.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":3} -->
<h3 class="has-text-align-center">Recent Articles,</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2020/02/building-bookmark-manager-using-nodejs-and-mysql/" class="rank-math-link">Building Bookmark Manager using nodejs and mysql</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2020/02/building-a-piano-with-react-hooks/" class="rank-math-link">Building a Piano with React Hooks</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":3} -->
<h3 class="has-text-align-center">Table of Content</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><a href="#firebase-setup" class="rank-math-link">Firebase Setup</a></li><li><a href="#integrating-firebase-with-react" class="rank-math-link">Integrating Firebase with React</a></li><li><a href="#developing-note-application" class="rank-math-link">Developing Note Application</a></li><li><a href="#summary" class="rank-math-link">Summary</a></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>If you are completely new to react development, checkout this course from <a href="https://ReactForBeginners.com/friend/CLOUDNWEB" class="rank-math-link">wesbos</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Well. It's Demo time..</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":2228,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://cloudnweb.dev/wp-content/uploads/2020/02/ezgif.com-video-to-gif-1.gif" alt="" class="wp-image-2228"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Let's how to build one something like this using firebase with react hooks.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":3} -->
<h3 class="has-text-align-center" id="firebase-setup">Firebase Setup</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Firstly, we will setup firebase and get the credentials for our application.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>goto <a href="https://console.firebase.google.com" class="rank-math-link">Firebase</a> and create a project</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":2229,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://cloudnweb.dev/wp-content/uploads/2020/02/firebase-setup-1-1024x651.png" alt="" class="wp-image-2229"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Click on Web to get the credentials for the project</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":2230,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://cloudnweb.dev/wp-content/uploads/2020/02/Screenshot-2020-02-20-at-1.02.07-AM.png" alt="" class="wp-image-2230"/></figure>
<!-- /wp:image -->

<!-- wp:image {"id":2231,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://cloudnweb.dev/wp-content/uploads/2020/02/firebase-setup-2-1024x928.png" alt="" class="wp-image-2231"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"align":"center","level":3} -->
<h3 class="has-text-align-center" id="integrating-firebase-with-react">Integrating firebase and react hooks</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>create a react project using create-react-app command,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npx create-react-app note-firebase
npm i firebase styled-components</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After that, create a file <strong>firebase.js</strong> and add the firebase credentials</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import firebase from "firebase/app";

import "firebase/firestore";

const firebaseConfig = {
  apiKey: `${process.env.APIKEY}`,
  authDomain: `${process.env.AUTH_DOMAIN}`,
  databaseURL: `${process.env.DATABASE_URL}`,
  projectId: `${process.env.PROJECTID}`,
  storageBucket: `${process.env.STORAGE_BUCKET}`,
  messagingSenderId: `${process.env.MESSAGE_SENDER_ID}`,
  appId: `${process.env.APP_ID}`,
  measurementId: `${process.env.MEASUREMENT_ID}`
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// firebase.analytics();

export default firebase;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>you might be wondering where do we set the environment variable, let's do that process,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm install env-cmd</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>env-cmd is used to set the environment variable in react applications. Then, add that in react scripts.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>"start": "env-cmd -f .env.development react-scripts start",</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p><strong>Note</strong>: Don't forget to create <strong>.env.development</strong> file and add the credentials.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":3} -->
<h3 class="has-text-align-center" id="developing-note-application">Developing Note Application with Firebase and Reack Hooks</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We will be using styled component for React Components. If you are new to the concept of styled component, checkout this <a href="https://www.robinwieruch.de/react-styled-components" class="rank-math-link">article</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Firstly, to check firebase is working correctly with react. let's connect it in the <strong>App.js</strong> to use firebase with react hooks.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import React from "react";
import "./App.css";

import firebase from "./firebase";

function App() {
  firebase
    .firestore()
    .collection("notes")
    .add({
      title: "Working",
      body: "This is to check the Integration is working"
    });
  return (
    &lt;div className="App">
      &lt;h2>Note Taking App&lt;/h2>
      &lt;p>using React Hooks and Firebase&lt;/p>
      &lt;h3>Notes : &lt;/h3>
    &lt;/div>
  );
}

export default App;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>it will insert the data into the notes collection. let's check whether it's working properly by running the command,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm run start</code></pre>
<!-- /wp:code -->

<!-- wp:image {"id":2237,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://cloudnweb.dev/wp-content/uploads/2020/02/Screenshot-2020-02-20-at-11.47.44-PM.png" alt="" class="wp-image-2237"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Woohoo..it's working.  Let's see how to implement it in our components.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create two files <strong>AddNote.js</strong> and <strong>NoteLists.js</strong> where <strong>AddNote</strong> is to Handle the logics for adding a note.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Whereas, NoteLists handles all the list items of notes. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>AddNote.js</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>add the following code in <strong>AddNote.js</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import React, { useState } from "react";
import styled from "styled-components";
import firebase from "./firebase";
const AddNoteDiv = styled.div`
  display: flex;
  width: 40%;
  flex-direction: column;
  margin: 30px auto;
  padding: 5px;
`;

const InputTitle = styled.input`
  padding: 0.5em;
  border: none;
  background: #f4f4;
  margin-bottom: 10px;
  border-radius: 3px;
`;

const BodyTextArea = styled.textarea`
  padding: 0.5em;
  border: none;
  height: 80px;
  background: #f4f4;
  margin-bottom: 10px;
  border-radius: 3px;
`;

const Button = styled.div`
  background: blue;
  color: white;
  font-size: 1em;
  padding: 10px;
  cursor: pointer;
  border-radius: 3px;
`;

const AddNote = () => {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

  const addNote = () => {
    firebase
      .firestore()
      .collection("notes")
      .add({
        title,
        body
      });

    setTitle("");
    setBody("");
  };

  return (
    &lt;AddNoteDiv>
      &lt;InputTitle value={title} onChange={e => setTitle(e.target.value)} />
      &lt;BodyTextArea value={body} onChange={e => setBody(e.target.value)} />
      &lt;Button onClick={addNote}>Add Note&lt;/Button>
    &lt;/AddNoteDiv>
  );
};

export default AddNote;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here, we create text area and text input and store those values in react state using <strong>useState</strong> Hooks.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Once the user Clicks the Add Note button, we send those state values to firebase.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>NoteLists.js</h4>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import React, { useState, useEffect } from "react";
import styled from "styled-components";
import firebase from "./firebase";

const ListsDiv = styled.div`
  width: 40%;
  height: 100%;
  background: #dedede;
  margin: 30px auto;
  padding: 20px;
`;

const ListItemDiv = styled.div`
  background: #b2c4db;
  border-radius: 5px;
  position: relative;
`;

const ListTitleDiv = styled.div`
  font-size: 24px;
  color: black;
  font-weight: bold;
  margin: 3px;
`;

const ListItemDetailDiv = styled.p`
  font-size: 18px;
  color: black;
  margin: 3px;
  max-height: 80px;
  overflow: auto;
`;

const ListItemDeleteButton = styled.button`
  border-radius: 5px;
  background: #c26c61;
  color: white;
  position: absolute;
  width: 15px;
  height: 15px;
  top: 5px;
  right: 10px;
  outline: none;
`;

function useLists() {
  const [lists, setLists] = useState([]);

  useEffect(() => {
    firebase
      .firestore()
      .collection("notes")
      .onSnapshot(snapshot => {
        const lists = snapshot.docs.map(doc => ({
          id: doc.id,
          ...doc.data()
        }));

        setLists(lists);
      });
  }, []);

  return lists;
}

const NoteLists = () => {
  const lists = useLists();

  const handleOnDelete = id => {
    firebase
      .firestore()
      .collection("notes")
      .doc(id)
      .delete();
  };

  return (
    &lt;ListsDiv>
      {lists.map(list => {
        return (
          &lt;ListItemDiv>
            &lt;ListTitleDiv>{list.title}&lt;/ListTitleDiv>
            &lt;ListItemDetailDiv>{list.body}&lt;/ListItemDetailDiv>
            &lt;ListItemDeleteButton onClick={() => handleOnDelete(list.id)} />
          &lt;/ListItemDiv>
        );
      })}
    &lt;/ListsDiv>
  );
};

export default NoteLists;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here, you might be wondering what is a <strong>useLists</strong>. you might have not seen something like this in React Hooks. well, it is a <a href="https://reactjs.org/docs/hooks-custom.html" class="rank-math-link">custom hook</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Why we need a Custom Hook?. That's a good question to ask. Before Hooks, if we want to share the stateful function or logic. we either use <a href="https://reactjs.org/docs/render-props.html" class="rank-math-link">Render Props</a> or <a href="https://reactjs.org/docs/higher-order-components.html" class="rank-math-link">Higher Order Components</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>After Hooks, we tend to use it for all our component development. How can share a stateful function which uses Hooks. There comes the concept of Custom Hooks.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Custom Hooks<strong> is a function whose name starts with use keyWord and it may call other Hooks</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Note : use KeyWord is for understanding purpose.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Like we said, Here <strong>useLists</strong> is a custom hook which calls the <strong>useState</strong> and <strong>useEffect</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Everytime data is added in the firebase, <strong>useLists</strong> hooks will be called to update the list state.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>App.js</strong> will be like</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import React from "react";
import AddNote from "./AddNote";
import NoteLists from "./NoteLists";
import "./App.css";

function App() {
  return (
    &lt;div className="App">
      &lt;h2>Note Taking App&lt;/h2>
      &lt;p>using React Hooks and Firebase&lt;/p>
      &lt;AddNote />
      &lt;h3>Notes : &lt;/h3>
      &lt;NoteLists />
    &lt;/div>
  );
}

export default App;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Complete Source code can be found <a href="https://github.com/ganeshmani/note-app-reacthooks-firebase" class="rank-math-link">here</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":3} -->
<h3 class="has-text-align-center" id="summary">Summary</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This article explains how to get started with firebase and react hooks. We will come up with some advanced Concepts in Firebase and React Hooks using a real time example in upcoming articles.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Until then, Happy Coding :-) </p>
<!-- /wp:paragraph -->