DEV Community

Cover image for Hooked on React JS
Christine Garaudy
Christine Garaudy

Posted on

Hooked on React JS

INTRODUCTION

React was developed by Facebook in response to their growing need for more efficient and manageable code as the social media giant continued to expand. Released in 2013, React was initially met with some skepticism from the developer community, but quickly proved its versatility and stability, winning over tons of teams looking for a way to make their applications faster and more responsive for their users. React is an open-source JavaScript library designed for building user interfaces comprised of components- functions that can accept properties and which describe how a portion of the UI should appear on the page and be rendered on the DOM. You declare a view for different states in the application, and React handles communicating the updating and re-rendering via the virtual DOM, which makes changes appear quickly for the user. Keeping code organized by building encapsulated components that manage their own state allows for quicker editing and debugging- hugely important for large scale applications like Facebook, but equally convenient for handling programs of any size.

LIFECYCLE IN REACT

Whether it is explicitly described in the code or not, all React class components undergo a four-part lifecycle: initialization (the component is constructed with its props and default state), mounting (the component is rendered onto the DOM), updating (the component is changed and the app is re-rendered and repainted), and unmounting (the component is removed from the DOM, freeing up related resources).


class Clock extends React.Component {
  constructor(props) { //initializes class with props and state
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
  //some code to run when component is rendered
  //maybe fetch some data
  }

  componentWillUnmount() {
  //perform cleanup after component is removed from DOM
  //cancel network request, clear a counter, etc
  }

  render() { //outputs its contents to DOM (required)
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date}.</h2>
      </div>
    );
  }
}

Formerly, only class components had access to these methods and the ability to handle state. Functional components simply output an element to the DOM. React developers changed all of that when they introduced hooks.

LET'S HOOK UP

Hooks were an experimental feature of React since 2018, but were officially introduced as part of React version 16.8, released February 2019. Hooks allow you to "hook into" lifecycle components without classes and give state to functional components, leading to code that is shorter and easier to read. Hooks are an "opt-in" feature, meaning that they are completely compatible with classes and won't break older code, allowing developers to easily experiment with implementing them into an existing codebase. Hooks can make components short and sweet:

//a class component

import React from "react"

class App extends React.Component {
   constructor() {
      super();
      this.state = {
         answer: 'Yes'
      }
   }

   render() {
      return (
         <div> 
            <h1> Is state important to know? {this.state.answer} </h1>
         </div>
      )
   }
}

export default App
//a functional component using hooks

//you must import hooks
import React, { useState } from "react"

function App() {
   const [ answer ] = useState('Yes')

   return (
      <div>
         <h1> Is state important to know? {answer} </h1>
      </div>
   )
}

export default App

Two of the most commonly seen hooks are useState and useEffect.

useState()

This method manages state to display. It makes use of array destructuring. Its first value is what you're saving as state, and the second is a function that lets you change that state.


import React, { useState } from "react"

function App() {
  const [count, setCount] = useState(0) //default value is 0

  function increment() {
     setCount(prevCount => prevCount + 1)
  }

  return (
    <div> 
      <h1> {count} </h1>
      <button onClick= {increment}> Increment! </button>
    </div>
  )
}

useEffect

useEffect effectively replaces lifecycle methods by allowing us to create side effects- reaching outside of the component to do something, like make a network request, listen for an event, or manipulate the DOM. It takes a callback function and array in which you can specify the variable(s) to watch for.

//with no second argument, runs the function on every component render

useEffect(() => {
   functionCall()
},)

//replaces componentDidMount by putting array as second arg, runs once

useEffect(() => {
   functionCall()
}, [])

/* replaces deprecated componentWillUpdate by adding variables to the array 
that it will watch for changes on */

useEffect(() => {
   functionCall()
}, [watch, these, variables])


//replaces componentWillUnmount if returning function to clean up side effects

useEffect(() => {
   function doStuff() {
     //effect
   }
   return function cleanup() {
     //remove effect
   }
}, [])

Additionally, React includes these more advanced built-in hooks: useContext, useReducer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect, useDebugValue. You can even create your own hooks for handling complex logic specific to your program's needs.

CONCLUSION

React is a simple, but powerful library for quickly building interactive user interfaces that are broken down into encapsulated components which contain their own state and abstract away much of the complexity of its rendering methods. The introduction of hooks further simplifies React components, making complicated class components unnecessary by allowing functional components to "hook into" lifecycle methods and providing the ability to share reusable state logic across multiple components. Code becomes cleaner, more concise, and easier to read and reason about. Best of all, hooks are completely compatible with older React code, allowing developers to opt-in and experiment with introducing them into existing programs without breaking anything. You can avail yourself to React's many useful built-in hooks, or even create your own.

Top comments (0)