Creating an Animated Tree Chart using React (Hooks) with D3

Creating an Animated Tree Chart using React (Hooks) with D3

This React Hooks tutorial explains how to create an Animated Tree Chart using React (Hooks) with D3. Animated Tree Chart – Using React (Hooks) with D3.

Creating an Animated Tree Chart – Using React (Hooks) with D3

Animated Tree Chart – Using React (Hooks) with D3

This is the code of the video tutorial series "Using React (Hooks) with D3".

Each tutorial session is saved within a branch, so if you wanna work with the code from this repo, checkout the branches!

This session is about creating an animated tree chart.

Code: https://github.com/muratkemaldar/using-react-hooks-with-d3/tree/10-hierarchy

React Hooks Tutorial for Beginners: Getting Started With React Hooks

React Hooks Tutorial for Beginners: Getting Started With React Hooks

React hooks tutorial for beginners, learn React hooks step by step: Introduction, useState Hook, useState with previous state, useState with object, useState with array, useEffect Hook, useEffect after render, Conditionally run effects, Run effects only once, useEffect with cleanup, useEffect with incorrect dependency, Fetching data with useEffect, useContext Hook, useReducer Hook, useReducer, Multiple useReducers, useReducer with useContext, Fetching data with useReducer, useState vs useReducer, useCallback Hook, useMemo Hook, useRef Hook

React Hooks Tutorial - 1 - Introduction

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

React Hooks Tutorial - 2 - useState Hook React Hooks Tutorial - 3 - useState with previous state React Hooks Tutorial - 4 - useState with object React Hooks Tutorial - 5 - useState with array React Hooks Tutorial - 6 - useEffect Hook React Hooks Tutorial - 7 - useEffect after render React Hooks Tutorial - 8 - Conditionally run effects React Hooks Tutorial - 9 - Run effects only once React Hooks Tutorial - 10 - useEffect with cleanup React Hooks Tutorial - 11 - useEffect with incorrect dependency React Hooks Tutorial - 12 - Fetching data with useEffect Part 1 React Hooks Tutorial - 13 - Fetching data with useEffect Part 2 React Hooks Tutorial - 14 - Fetching data with useEffect Part 3 React Hooks Tutorial - 15 - useContext Hook Part 1 React Hooks Tutorial - 16 - useContext Hook Part 2 React Hooks Tutorial - 17 - useContext Hook Part 3 React Hooks Tutorial - 18 - useReducer Hook React Hooks Tutorial - 19 - useReducer (simple state & action) React Hooks Tutorial - 20 - useReducer (complex state & action) React Hooks Tutorial - 21 - Multiple useReducers React Hooks Tutorial - 22 - useReducer with useContext React Hooks Tutorial - 23 - Fetching data with useReducer Part 1 React Hooks Tutorial - 24 - Fetching data with useReducer Part 2 React Hooks Tutorial - 25 - useState vs useReducer React Hooks Tutorial - 26 - useCallback Hook React Hooks Tutorial - 27 - useMemo Hook React Hooks Tutorial - 28 - useRef Hook Part 1 React Hooks Tutorial - 29 - useRef Hook Part 2 React Hooks Tutorial - 30 - Custom Hooks React Hooks Tutorial - 31 - useDocumentTitle Custom Hook React Hooks Tutorial - 32 - useCounter Custom Hook React Hooks Tutorial - 33 - useInput Custom Hook

State Management with React Hooks and RxJS

State Management with React Hooks and RxJS

In this article, we’ll cover the basics of RxJS and how to integrate it with React applications using React Hooks for state management.

In this article, we’ll cover the basics of RxJS and how to integrate it with React applications using React Hooks for state management. We’ll do this by building a demo chat application. Our chat application will have three components that will communicate with each other through RxJS.

Our final app will look like this:

Let’s start by explaining RxJS

RxJS (Reactive Extensions Library for JavaScript) is a useful library for reactive programming. The RxJS documentation uses this definition:

RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.

Reactive programming is an event-based paradigm that allows us to run asynchronous sequences of events as soon as data is pushed to a consumer.

To be able to use RxJS for state management in React, it is important to understand the following key terms:

Observable

An Observable is a data stream that houses data that can be passed through different threads. In our demo app, we’ll be using an Observable to supply data to our different components.

Observer

An Observer consumes the data supplied by an Observable. In our demo app, we’ll be using our setState Hook to consume data from our Observable.

Subscription

In order for our Observer to consume data from our Observable, we’ll have to subscribe it to the Observable. In our demo app, we’ll be using the subscribe() method to subscribe our setState Observer to our Observable.

Setting up our application

The best way to understand RxJS is to use it.

Let’s start by creating a new react application. If you don’t have create-react-app installed, on your terminal, run:

>npm i -g create-react-app

Next:

create-react-app rxjs_react_chat

This will generate a new react application using create-react-app.

To start our application, let’s navigate to our new app directory and run the command npm start:

cd rxjs_react_chat
npm start

In our new generated app directory, let’s navigate to /src/. Since we’ll be working with multiple components, let’s set up BrowserRouter for navigating through different routes.

Let’s run the following command:

npm install --save react-router-dom

Next, we’ll edit our /src/App.js file to look like this:

// /src/App.js
import  React  from  'react';
import { BrowserRouter, Route, Switch } from  'react-router-dom';
import  './index.css';

const  App  = () => (
  <BrowserRouter />
);

export  default  App;

In our src folder, let’s create a store directory, src/store. This is where we’ll house our store.

Next, let’s create a chat.js file for our chat operations, src/store/chat.js. In our chat.js file, we’ll import Subject from rxjs and create a new variable from the Subject class:

import { Subject } from 'rxjs';

const subject = new Subject();

Subjects and Subscriptions

An RxJS Subject can act as both an Observable and an Observer at the same time. In this way, values can be multicasted to many Observers from it so that when a Subject receives any data, that data can be forwarded to every Observer subscribed to it.

In our application, we’ll be subscribing our different React Hooks setState functions to our RxJS Subject so that when it receives any data, it forwards that data to every state associated with our setState function.

Let’s create a subscribe method for this purpose:

import { Subject } from 'rxjs'

const subject = new Subject();

const chatStore = {
  subscribe: setState => subject.subscribe(setState)
}

Next, we’ll create an object for our initial chat state:

import { Subject } from 'rxjs'

const subject = new Subject();

const initialState = {
  data: [],
  newDataCount: 0,
}; 

let state = initialState;

const chatStore = {
  subscribe: setState => subject.subscribe(setState)
}

We’ll use the data key to hold our array of message objects. These message objects will contain the values person (to specify who a message is from) and text (to store the message text).

Here’s what our object will look like:

{
  person: 'first-person',
  text: 'How are you?'
}

In our initialState object, the newDataCount will be used by our notification functionality to tell when new data has been pushed to our state.

Now that we have our state object, let’s create an init() method that will initialize our component’s state whenever it’s mounted:

...
const chatStore = {
  init: () => subject.next(state),
  subscribe: setState => subject.subscribe(setState)
}

The Subject.next() method is used to feed a new value to the Subject. When we call the next() method with a value as its parameter, that value is multicasted to all Observers subscribed to the Subject.

In our application, we’ll call both the subscribe() and init() methods whenever our component mounts in order to set our state to what we have in our chat store.

Adding data to the store

Next we’ll create a sendMessage() method. We’ll call this method whenever our users hit the send message button. Our sendMessage() method will receive a message argument, which we’ll append to our state.data array. Remember that our message argument is an object with keys person and text.

Let’s create our object with the following code block:

...
const chatStore = {
  init: () => subject.next(state),
  subscribe: setState => subject.subscribe(setState),
  sendMessage: message => {
    state = {
      ...state,
      data: [...state.data, message],
      newDataCount: state.newDataCount + 1
     };
     subject.next(state);
  }
};

In our new block, we appended our message object to our state.data array, then we incremented our newDataCount.

Now that we have our newDataCount incremented every time a new message is sent by a user, we’ll also add a functionality for resetting our new data count each time the messages are viewed so that when person 1 sends a new message and person 2 reads the message, the data count resets to 0.

To do this, in our init() method, we’ll assign the newDataCount key in our state the value of 0 each time a new component that subscribes to our Subject is mounted:

...
const chatStore = {
  init: () => {
    state = {...state, newDataCount: 0},
    subject.next(state)
  },
  subscribe: setState => subject.subscribe(setState),
  sendMessage: message => {
    state = {
      ...state,
      data: [...state.data, message],
      newDataCount: state.newDataCount + 1
    };
    subject.next(state);
  }
};

Removing data from the store

Next, we’ll add a method for clearing all messages. We’ll call it clearChat():

...
const chatStore = {
  init: () => {
    <b>state = {...state, newDataCount: 0},</b>
    subject.next(state)
  },
  subscribe: setState => subject.subscribe(setState),
  sendMessage: message => {
    state = {
      ...state,
      data: [...state.data, message],
      newDataCount: state.newDataCount + 1
    };
    subject.next(state);
  },
  clearChat: () => {
    state = initialState;
    subject.next(state);
  },
  initialState
};

We’ve also added our initial state to the chatStore object. We’ll use this to set our initial state value when defining our chatState with the useState() Hook.

Finally, let’s export the chatStore object. Our src/store/chat.js file should now look like this:

// src/store/chat.js

import { Subject } from 'rxjs';

const subject = new Subject();
const initialState = {
  status: '',
  data: [],
  newDataCount: 0,
  error: ''
};

let state = initialState;

const chatStore = {
  init: () => {
    state = {...state, newDataCount: 0}
    subject.next(state)
  },
  subscribe: setState => subject.subscribe(setState),
  sendMessage: message => {
    state = {
      ...state,
      data: [...state.data, message],
      newDataCount: state.newDataCount + 1
    };
    subject.next(state);
  },
  clearChat: () => {
    state = {...state, data: []};
    subject.next(state);
  },
  initialState
};

export default chatStore;
Using the store

Now that we’ve set up our chat store, in the following steps, we’ll be creating our components to utilize the store and its methods.

First, let’s modify our src/index.css file to look like this:

.container {
  font-family: Arial, Helvetica, sans-serif;
  padding: 1em;
}

.chat-box {
  background: #202020;
  margin: auto;
  padding: 2em;
  height: 35em;
  width: 95%;
  border-radius: 20px;
  overflow-y: scroll;
}

.first-person, .second-person {
  display: inline-block;
  color: #fff;
  height: 25px;
  min-width: 20%;
  max-width: 60%;
  padding: 20px;
  text-align: center;
  vertical-align: middle;
  border-radius: 30px;
}

.first-person {
  background: rgb(0, 173, 231);
}

.second-person {
  background: #06c406;
  float: right;
}

.clear{ 
  clear: both;
  display: block;  
  content: "";
  width: 100%;  
}

.switcher-div {
  padding-top: 1em;
  text-align: center;
}

#messageForm {
  text-align: center;
  margin-top: 1.5em;
}

#messageForm input {
  height: 2em;
  width: 23em;
  border-radius: 3em;
  padding: 1em;
}

#messageForm button {
  margin-left: 2em;
  height: 2.7em;
  width: 6.2em;
  border-radius: 25px;
  border: none;
  cursor: pointer;
}

.clear-button {
  background: #d40000;
  color: #fff;
  float: right;
  margin-right: 3em;
  text-align: center;
  height: 2.5em;
  width: 8em;
  cursor: pointer;
}

.switcher {
  background: #cecece;
  color: #141414;
  height: 2.5em;
  width: 6em;
  border-radius: 25px;
  border: 1 px solid black;
  margin-right: 1em;
  cursor: pointer;
}

.notify {
  position: absolute;
  background: #db0000;
  color: white;
  height: 1em;
  width: 1em;
  border-radius: 100%;
  padding: 0.15em;
  margin-left: 0.5em;
  margin-top: -0.5em;
}

In our src folder, let’s create a components directory, src/components. This is where we’ll house all our components. We’ll need three components for our application:

  • A component for the first person
  • A component for the second person
  • A component for switching between the two person components

In our src/components directory, let’s create a new file, FirstPerson.js, for our first person component. Our new component should look like this:

import  React, { useState } from  "react";

const FirstPerson = () => {
  const [chatState, setChatState] = useState({});
  return (
    <div className="container">
      <h2>Mycroft</h2>
      <div className="chat-box">
        {chatState.data.map(message => (
          <div>
            <p className={message.person}>{message.text}</p>
            <div className="clear"></div>
          </div>
        ))}
      </div>
      <form id="messageForm">
        <input
          type="text"
          id="messageInput"
          name="messageInput"
          placeholder="type here..."
          required
        />
        <button type="submit">Send</button> <br />
      </form>
    </div>
  );
}

export  default  FirstPerson;

Subscribing to our store and retrieving existing data

In the next block, we’ll import our chatStore and use its initialState property as our default chatState value.

Then, in our useLayoutEffect() Hook, we’ll subscribe our setChatState function to our chat store using the chatStore.subscribe() method and, finally, use the chatStore.init() method to initialize our component’s chatState:

import React, { useState, useLayoutEffect } from "react";
<b>import chatStore from '../store/chat';</b>

const FirstPerson = () => {
  const [chatState, setChatState] = useState(chatStore.initialState);

  useLayoutEffect(()=> {
    chatStore.subscribe(setChatState);
    chatStore.init();
  },[]);

  return (...)

We are making use of the useLayoutEffect() Hook to send data to our chatState before our component is rendered.

To preview the result of our code so far, let’s create an index.js file in our src/components folder and export our FirstPerson component from it:

// src/components/index.js
export {  default as FirstPerson } from './FirstPerson';

Next, we’ll import our FirstPerson component in our src/App.js file and add it to a route path:

// /src/App.js
import  React  from  'react';
import { BrowserRouter, Route, Switch } from  'react-router-dom';
import { FirstPerson } from './components';
import  './index.css';

const  App  = () => (
    <BrowserRouter>
      <>
        <Switch>
          <Route path="/" component={FirstPerson} exact />
          <Route path="/first-person" component={FirstPerson} exact />
        </Switch>
      </>
   </BrowserRouter>
);

export  default  App;

Now, when we run our app and navigate to the / or /first-person route, we should see:

Back to our /src/components/FirstPerson.js file. Let’s add an onFormSubmit() method. We’ll call this method whenever our user clicks the send button:

...

const FirstPerson = () => {
  const [chatState, setChatState] = useState(chatStore.initialState);

  useLayoutEffect(()=> {
    chatStore.subscribe(setChatState);
    chatStore.init();
  },[]);

  const onFormSubmit = e => {
    e.preventDefault();
    const messageObject = {
      person: 'first-person',
      text: e.target.elements.messageInput.value.trim(),
    };
    chatStore.sendMessage(messageObject);
    document.getElementById('messageForm').reset();
  };

  return (
    ...
      <form id="messageForm" onSubmit={onFormSubmit}>
        <input
          type="text"
          id="messageInput"
          name="messageInput"
          placeholder="type here..."
          required
        />
        <button type="submit">Send</button> <br />
      </form>
    </div>
  );
}

export default FirstPerson;

Our onFormSubmit() function creates a message object with the person and text keys, then uses our chatStore.sendMessage() method to add our new message to the chat store.

Next, we’ll add a button that we’ll use to call our chatStore.clearChat() method. We’ll use this to clear our chat store whenever the clear button is clicked.

Let’s add the following block of code right after the </form> closing tag:

<button className="clear-button" onClick={() => chatStore.clearChat()}>
  Clear Chat
</button>

Our src/components/FirstPerson.js file should now look like this:

import React, { useState, useLayoutEffect } from "react";
import chatStore from '../store/chat';

const FirstPerson = () => {
  const [chatState, setChatState] = useState(chatStore.initialState);

  useLayoutEffect(()=> {
    chatStore.subscribe(setChatState);
    chatStore.init();
  },[]);

  const onFormSubmit = e => {
    e.preventDefault();
    const messageObject = {
      person: 'first-person',
      text: e.target.elements.messageInput.value.trim(),
    };
    chatStore.sendMessage(messageObject);
    document.getElementById('messageForm').reset();
  };

  return (
    <div className="container">
      <h2>Mycroft</h2>
      <div className="chat-box">
        {chatState.data.map(message => (
          <div>
            <p className={message.person}>{message.text}</p>
            <div className="clear"></div>
          </div>
        ))}
      </div>
      <form id="messageForm" onSubmit={onFormSubmit}>
        <input
          type="text"
          id="messageInput"
          name="messageInput"
          placeholder="type here..."
          required
        />
        <button type="submit">Send</button> <br />
      </form>
      <button className="clear-button" onClick={() => chatStore.clearChat()}>
        Clear Chat
      </button>
    </div>
  );
}

export default FirstPerson;

When we preview our app on our browser, we should now be able to send a message to our store and clear all messages:

[IMAGE]

Sharing data among components

Now that we’ve seen how to retrieve data from our store and add data to it, let’s create our SecondPerson component to demonstrate how this data can be shared between different components.

The SecondPerson component has the same functionality as the FirstPerson component, so we’ll only change our person value in our messageObject to second-person and the name of our user from Mycroft to Cortana in the <h2> tag inside our container div.

To do this, let’s create a new file, src/components/SecondPerson.js, and paste the following code blocks:

import React, { useState, useLayoutEffect } from "react";
import chatStore from '../store/chat';

const SecondPerson = () => {
  const [chatState, setChatState] = useState(chatStore.initialState);

  useLayoutEffect(()=> {
    chatStore.subscribe(setChatState);
    chatStore.init();
  },[]);

  const onFormSubmit = e => {
    e.preventDefault();
    const messageObject = {
      person: 'second-person',
      text: e.target.elements.messageInput.value.trim(),
    };
    chatStore.sendMessage(messageObject);
    document.getElementById('messageForm').reset();
  };

  return (
    <div className="container">
      <h2 style={{float: 'right'}}>Cortana</h2>
      <div className="chat-box">
        {chatState.data.map(message => (
          <div>
            <p className={message.person}>{message.text}</p>
            <div className="clear"></div>
          </div>
        ))}
      </div>
      <form id="messageForm" onSubmit={onFormSubmit}>
        <input
          type="text"
          id="messageInput"
          name="messageInput"
          required
        />
        <button type="submit">Send</button> <br />
      </form>
      <button className="clear-button" onClick={() => chatStore.clearChat()}>
        Clear Chat
      </button>
    </div>
  );
}

Next, we’ll need to create our PersonSwitcher component to switch between our two components. In our src/components directory, let’s create a new file, PersonSwitcher.js, and paste the following code blocks:

// src/components/PersonSwitcher.js
import React, {useState, useEffect} from 'react';
import { Link } from 'react-router-dom';
import chatStore from '../store/chat';

const PersonSwitcher = () => {
  const [chatState, setChatState] = useState(chatStore.initialState);
  const location = window.location.href.split('/')[3];

  useEffect(() => {
    chatStore.subscribe(setChatState);
    chatStore.init();
  }, [])

  const messageNotification = chatState.newDataCount > 0
    && (<span className="notify">{chatState.newDataCount}</span>);

  return (
    <div className="switcher-div">
      <Link to="/first-person"><button className="switcher">
        Person1
        {location !== 'first-person' && location.length > 1 && messageNotification}
      </button></Link>
      <Link to="/second-person"><button className="switcher">
        Person2
        {location !== 'second-person' && messageNotification}        
      </button></Link>
    </div>
  );
}

export default PersonSwitcher;

Notice that we’ve also created a chatState for our component, which we’ve subscribed to our chatStore. We’ll need this to notify our component when a new message is added to our chat store. Note how we added a messageNotification variable that utilizes our newDataCount property from our chat store.

Now, we can export our two new components from our src/components/index.js folder:

export { default as FirstPerson } from './FirstPerson';
export { default as SecondPerson } from './SecondPerson';
export { default as PersonSwitcher } from './PersonSwitcher';

Finally, let’s import our new components in our src/App.js and add them to our BrowserRouter. Our App.js file should now look like this:

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { FirstPerson, SecondPerson, PersonSwitcher } from './components';
import './App.css';

const App = () => (
  <Router>
    <>
      <PersonSwitcher />
      <Switch>
        <Route path="/" component={FirstPerson} exact />>
        <Route path="/first-person" component={FirstPerson} exact />>
        <Route path="/second-person" component={SecondPerson} exact />>
      </Switch>
    </>
  </Router>
);

export default App;

Now when we run our application, we’ll be able to switch between components, receive new message count when we send a message, and clear all messages using the clear button:

Conclusion

In this article, we’ve covered the basics of RxJS and have demonstrated how to use it for state management in React by building a component-based chat application. Here’s a link to the GitHub repo for our demo app.

Compared to other alternatives like Redux, I’ve found the use of RxJS and Hooks to be a really effective and straightforward way to manage state in React applications.

React Hooks Tutorial: Learn `useState` and `useEffect` in 5 minutes

React Hooks Tutorial: Learn `useState` and `useEffect` in 5 minutes

Sometimes 5 minutes is all you've got. So in this article, we're just going to touch on two of the most used hooks in React: `useState` and `useEffect`.

Sometimes 5 minutes is all you've got. So in this article, we're just going to touch on two of the most used hooks in React: useState and useEffect.

If you're not famliar with hooks, here's the TL;DR: because of hooks, there's almost no more need for class-based components. Hooks let you "hook into" the underlying lifecycle and state changes of a component within a functional component. More than that, they often also improve readability and organization of your components.

useState

Let's begin with a functional component.

import React from 'react';

function App() {
  return (
    <div>
      <h1>0</h1>
      <button>Change!</button>
    </div>
  );
}

As you can see, nothing fancy at the moment. We're just rendering some text and a (useless) button.

Now let's import our very first hook, useState to learn how to handle state in our functional component.

As this hook is a function, let's console.log what we get returned from it.

import React, { useState } from 'react';

function App() {
  const value = useState();
  console.log(value);

  return (
    <div>
      <h1>0</h1>
      <button>Change!</button>
    </div>
  );
}

In the console, we get an array

> [null, ƒ()]

And when we pass an argument to useState

const value = useState(true);

In the console, we get an array with our value as the first member.

> [true, ƒ()]

Now, in our component, we can access our state at value[0] and render it in <h1> instead of a hardcoded value.

import React, { useState } from 'react';

function App() {
  const value = useState(0);
  console.log(value); // [0, ƒ()]

  return (
    <div>
      <h1>{value[0]}</h1>
      <button>Change!</button>
    </div>
  );
}

We can improve our code by using array destructuring to store the value from useState hook. It's similar to object destructuring, which tends to be a bit more commonly seen. In case you're not super familiar with object destructuring, here's a quick recap:

const person = {
  name: 'Joe',
  age: 42
};

// creates 2 const values from person object
const { name, age } = person;
console.log(name); // 'Joe'
console.log(age); // 42

Array destructing is almost the same, but uses square brackets [] instead of curly braces {}.

A quick tip: in object destructuring, the names of created variables must match the names of properties in the object. For array destructuring, that's not the case. It's all about the order. The benefit here is we can name the items whatever we want.

Using array destructuring, we can get the initial value of state from the useState() hook.

import React, { useState } from 'react';

function App() {
  // remember, there's a second item from the array that's missing here, but we'll come right back to use it soon
  const [count] = useState(0);  

  return (
    <div>
      <h1>{count}</h1>
      <button>Change!</button>
    </div>
  );
}

OK, we've got the initial state value. How do we change the value in the state with hooks?

Remember that useState() hook returns an array with 2 members. The second member is a function that updates the state!

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

You can, of course, call it what you wish, but by convention, it's normally called with prefix "set-", and then whatever state variable we wish to update was called, so setCount it is.

It's simple to use this function. Just call it and pass the new value you want that state to have! Or, just like this.setState in a class component, you can pass a function that receives the old state and returns the new state. Rule of thumb: do this anytime you need to rely on the past state to determine the new state.

To call it, we'll pass it to the onClick event listener. And just like with a regular setState in a class-based component, we can pass our state update to setCount.

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

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>
        Change!
      </button>
    </div>
  );
}

We can clean this up a bit, by extracting our state update to a separate function.

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

  function change() {
    setCount(prevCount => prevCount + 1);
  }

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={change}>Change!</button>
    </div>
  );
}

Great! And now when we can see the counter going up when we click the button.

Of course, useState can get a lot more complicated than this, but we've only got 5 minutes here, so let's move on to the next hook for now.

useEffect

Hooks have simplified quite a few things, compared to the way things were in class-based components. Previously we needed to know a bit about lifecycle methods and which one is best suited for which situation. useEffect hook simplified this situation. If you wish to perform side effects, network request, manual DOM manipulation, event listeners or timeouts and intervals.

useEffect hook can be imported just like useState.

import React, { useState, useEffect } from 'react';

To make useEffect do something, we pass it an anonymous function as an argument. Whenever React re-renders this component, it will run the function we pass to useEffect.

useEffect(() => {
  /* any update can happen here */
});

This is what the whole code might look like.

import React, { useState, useEffect } from 'react';

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

  function change() {
    setCount(prevCount => prevCount + 1);
  }

  useEffect(() => {
    /* any update can happen here */
  });

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={change}>Change!</button>
    </div>
  );
}

export default App;

As an example, we will use a nice npm package that generates a random color. Feel free to write your own if you wish of course, but for this tutorial, we will just install it, npm i randomcolor, and import.

import randomcolor from 'randomcolor';

Let's now use our knowledge about useState hook to store some random color in the state.

const [color, setColor] = useState(''); // initial value can be an empty string

We then can then assign the color of the counter we already have.

<h1 style={{ color: color }}>{count}</h1>

Now, just for the sake of it, let's change the color of the counter on every click of the Change! button. useEffect will run every time the component re-renders, and the component will re-render every time the state is changed.

So if we write the following code, it would get us stuck in an infinite loop! This is a very common gotcha with useEffect

useEffect(() => {
  setColor(randomcolor());
});

setColor updates state, which re-renders the component, which calls useEffect, which runs setColor to update the state, which re-renders the component... Yikes!

We probably only want to run this useEffect when the count variable changes.

To tell useEffect which variable(s) to keep track of, we give an array of such variables as a second argument.

useEffect(() => {
  setColor(randomcolor());
}, [count]);

This basically says "only run this effect if the count state changes. This way we can change the color and not cause our effect to run infinitely.

Conclusion

There's a lot more to learn about hooks, but I hope you've enjoyed this quick 5-minute peek into hooks.

Happy coding 🤠