Learning React Hooks: Part 3: States and Effects

Learning React Hooks

React hooks provide functionality to “hook into” React properties and life-cycle values outside of component classes.


States and Effects

In the previous part, the word “normally” was used as part of an explanation that functions do not have states. And this is true: they do not. However, starting with React 16.8, it is possible to use “hooks” to grant functions state-like functionality and have them be aware of the React lifecycle.

useState()

Starting in React 16.8, the hook useState() was introduced. It accepts a value and returns an array containing two entries: a single value and a single function to change the value.

A common usage pattern might look like the following:

const [value, setValue] = useState(initialValue);

In the above code, the variable containing the initial value is value and the function to change it is setValue(). The initial value passed to the function is, of course, initialValue.

Note: While the name setValue is not important to its usage, it is highly recommended to create a function name matching the name of the variable used. For example, if book was the variable name, a highly recommended function name would be setBook() to avoid confusion.

Consider the following code:

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

function Example(props) {

  const [example, setExample] = useState(props.exampleValue);

  return (
    <div>
      <p 
        onClick={() => setExample(example + 1)}>
          Show the example value: {example}.
      </p>
      <p>
        Show the props.exampleValue: {props.exampleValue}.
      </p>
    </div>
  );
}

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      example: 1
    };

  }


  render() {
    return(
      <div>
        <Example exampleValue={this.state.example} />
      </div>
    );
  }
}

export default App;

In the above code, the function useState() is within a function named Example that calls the function setExample() internally. This works like setState() would within a component: it changes the value and re-renders the content.

The difference between setState() and the newer use of useState() has to do with its own usage: useState() changes a single value whereas setState() can, potentially, merge multiple changes within a component class’s state.

useEffect()

Like with how useState() allows for state-like design patterns within a function, the useEffect() provides a way to react after content has been rendered and perform additional tasks within a function.

The use of the function useEffect() is similar to those within a component class using the built-in componentDidMount() or componentDidUpdate() functions.

Conceptually, an “effect” in React is some additional change and so useEffect() calls any function passed to it after a render event has happened within the function in which it is defined. Calls to a function defined by setState(), for example, would also trigger it.

Consider the following code:

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

function Example(props) {

  const [example, setExample] = useState(props.exampleValue);

  useEffect(
    () => {
      document.title = `Example is ${example}`;
    }
  );

  return (
    <div>
      <p 
        onClick={() => setExample(example + 1)}>
          Show the example value: {example}.
      </p>
      <p>
        Show the props.exampleValue: {props.exampleValue}.
      </p>
    </div>
  );
}

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      example: 1
    };

  }


  render() {
    return(
      <div>
        <Example exampleValue={this.state.example} />
      </div>
    );
  }
}

export default App;

In the above code, the document.title is set to the initial value of example within the function. However, additional calls made to useState() via its usage in the onClick event listener causes the content to be re-rendered and for useEffect() to be called as a result. Any click on the text increases the local, stateful value and causes the document.title to be updated with the new value.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.