DEV Community

Cover image for Hook, Line, and Sinker: Hooks in React.js
Peter Klingelhofer
Peter Klingelhofer

Posted on • Updated on

Hook, Line, and Sinker: Hooks in React.js

Introduction

React is a JavaScript library for building user interfaces, and is a tool used primarily for building the view layer of an application. In React, are made up of components using code to produce HTML. Respecting the separation of concerns, each component is responsible for a separate function or task.

React was created by a software engineer at Facebook named Jordan Walke, which was later incorporated into the Facebook newsfeed in 2011, used in Instagram in 2012, made open source at JSConf in 2013, and adopted by Netflix in 2015. In 2017, they fully rewrote React's internals to modernize it, and in 2019, Hooks were released, a means of sharing stateful logic between components.

Static components are React components that are not updated constantly. Stateful components are dynamic (like a counter for example) and re-render constantly.

When props or states change in React, the component tree re-renders, updating the user interface with the latest data. Typically useState is used for this rendering and re-rendering process.

Alt Text

Hooks - Introducing useState

For values that will change, you'll want to store said values using React state, using React hooks. Hooks allow us to link, or hook up, functionality across components. Importing React's useState hook can be done like so:

import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

An example of a value that might change would be a numeric tally of the number of reviews a product has received.

function ReviewsCount() {
  const [reviewsCount, setReviewsCount] = useState(0);

function anotherReviewAdded() {
  setReviewsCount(lastState => lastState ++);
}

  return (
    <div>
      {reviewsCount} Reviews
      <br />
      <button onClick={anotherReviewAdded}>
        Submit Review
      </button>
    </div>
  );
}

ReactDOM.render(
  <reviewsCount />,
  document.getElementById('reviewsCount')
);
Enter fullscreen mode Exit fullscreen mode

Hooks - Introducing useEffect

useEffect is an important addition to your repertoire if you aim to cause side effects, e.g do something that isn't part of the return. Say we wanted to send a message to the console.log to see if a boolean was checked.

function ConsoleBoolean() {
  const [clicked, setTrue] = useState(false);

  useEffect(() => {
    console.log(`Boolean True!`);
  });

  return (
    <>
      <input
        type="checkbox"
        value={clicked}
        onChange={() => setTrue((clicked) => !clicked)}
      />
      {clicked ? 'clicked' : 'not clicked'}
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

Alt Text

Hooks - Introducing useContext

useContext returns a context value for the context specified. When the <MyContext.Provider> updates, the useContext hook triggers a rerender passing the latest context value. The argument useContext receives is the context object itself.

Context using the standard way:

import React from "react";

const ColorContext = React.createContext();

function App() {
  return (
    <ColorContext.Provider color={blue}>
      <div>
        <Display />
      </div>
    </ColorContext.Provider>
  );
}

function Interface() {
  return (
    <ColorContext.Consumer>
      {value => <div>The color is {color}.</div>}
    </ColorContext.Consumer>
  );
}
Enter fullscreen mode Exit fullscreen mode

Context using the new useContext hook:

import React, { useContext } from 'react';

function Interface() {
  const color = useContext(NumberContext);
  return <div>The color is {color}.</div>;
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

React.js is one of the most widely used libraries in JavaScript today, providing a powerful means of constructing the view layer of applications. We can use hooks to have the various components in React talk to each other, and cause changes and perform functions upon changes to the state and upon user interaction. useState allows you to add state to your components, storing values that will probably change. useEffect is important to use when we need a render to cause side effects outside of just the return of the function. useContext can be used to rerender when its value changes. These hooks allow you to use state and other features without writing a class.

Top comments (0)