Key Concepts

Review core concepts you need to learn to master this subject

Function Components

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

In React, you can use a function as a component instead of a class. Function components receive props as a parameter.

In the example code, we show two equivalent components: one as a class and one as a function.

Why Hooks?

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

Hooks are functions that let us “hook into” state and lifecycle functionality in function components.

Hooks allow us to:

  • reuse stateful logic between components
  • simplify and organize our code to separate concerns, rather allowing unrelated data to get tangled up together
  • avoid confusion around the behavior of the this keyword
  • avoid class constructors, binding methods, and related advanced JavaScript techniques

Rules for Using Hooks

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

There are two main rules to keep in mind when using Hooks:

  1. Only call Hooks from React functions
  2. Only call Hooks at the top level, to be sure that Hooks are called in the same order each time a component renders.

Common mistakes to avoid are calling Hooks inside of loops, conditions, or nested functions.

The State Hook

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

The useState() Hook lets you add React state to function components. It should be called at the top level of a React function definition to manage its state.

initialState is an optional value that can be used to set the value of currentState for the first render. The stateSetter function is used to update the value of currentState and rerender our component with the next state value.

State Setter Callback Function

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

When the previous state value is used to calculate the next state value, pass a function to the state setter. This function accepts the previous value as an argument and returns an updated value.

If the previous state is not used to compute the next state, just pass the next state value as the argument for the state setter.

Multiple State Hooks

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

useState() may be called more than once in a component. This gives us the freedom to separate concerns, simplify our state setter logic, and organize our code in whatever way makes the most sense to us!

Side Effects

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

The primary purpose of a React component is to return some JSX to be rendered. Often, it is helpful for a component to execute some code that performs side effects in addition to rendering JSX.

In class components, side effects are managed with lifecycle methods. In function components, we manage side effects with the Effect Hook. Some common side effects include: fetching data from a server, subscribing to a data stream, logging values to the console, interval timers, and directly interacting with the DOM.

The Effect Hook

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

After importing useEffect() from the 'react' library, we call this Hook at the top level of a React function definition to perform a side effect. The callback function that we pass as the first argument of useEffect() is where we write whatever JavaScript code that we’d like React to call after each render.

Effect Cleanup Functions

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

The cleanup function is optionally returned by the first argument of the Effect Hook.

If the effect does anything that needs to be cleaned up to prevent memory leaks, then the effect returns a cleanup function. The Effect Hook will call this cleanup function before calling the effect again as well as when the component is being unmounted from the DOM.

Multiple Effect Hooks

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

useEffect() may be called more than once in a component. This gives us the freedom to individually configure our dependency arrays, separate concerns, and organize our code in whatever way makes the most sense to us!

Effect Dependency Array

// The two components below are equivalent. class GreeterAsClass extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } function GreeterAsFunction(props) { return <h1>Hello, {props.name}!</h1>; }

The dependency array is used to tell the useEffect() method when to call our effect.

By default, with no dependency array provided, our effect is called after every render. An empty dependency array signals that our effect never needs to be re-run. A non-empty dependency array signals to the Effect Hook that it only needs to call our effect again when the value of one of the listed dependencies has changed.

Arrow Chevron Left Icon
Function Components
Lesson 1 of 3
Arrow Chevron Right Icon
  1. 1
    In the code editor, take a look at Example.js. The first Example component is defined as a JavaScript class, but it doesn’t have to be! In React, we can also define components as JavaScript fu…
  2. 2
    Like any component, function components can receive information via props. To access these props, give your function component a parameter named props. Within the function body, you can access th…
  3. 3
    Well done! You’ve written your first function component. Here’s a recap: * Function components are React components defined as JavaScript functions * Function components must return JSX * Functi…
  1. 1
    As React developers, we love breaking down complex problems into simple pieces. Classes, however, are not simple. They: * are difficult to reuse between components * are tricky and time-consumi…
  2. 2
    Let’s get started with the State Hook, the most common Hook used for building React components. The State Hook is a named export from the React library, so we import it like this: import React, { …
  3. 3
    Great work building out your first stateful function component in the last exercise. Just like you used the State Hook to manage a variable with string values, we can use the State Hook to manage t…
  4. 4
    Let’s see how to manage the changing value of a string as a user types into a text input field: import React, { useState } from ‘react’; export default function EmailTextInput() { const [email…
  5. 5
    Often, the next value of our state is calculated using the current state. In this case, it is best practice to update state with a callback function. If we do not, we risk capturing outdated, or “s…
  6. 6
    Think about the last time that you ordered a pizza online. Mmmmm… Part of the magical website that brought you tasty food was built with code like this: import React, { useState } from “react”; …
  7. 7
    When we work with a set of related variables, it can be very helpful to group them in an object. Let’s look at an example! export default function Login() { const [formState, setFormState] = use…
  8. 8
    While there are times when it can be helpful to store related data in a data collection like an array or object, it can also be helpful to separate data that changes separately into completely diff…
  9. 9
    Awesome work, we can now build “stateful” function components using the useState React Hook! Let’s review what we learned and practiced in this lesson: * With React, we feed static and dynamic d…
  1. 1
    Before Hooks, function components were only used to accept data in the form of props and return some JSX to be rendered. In the last lesson, we defined function components that use the State Hook t…
  2. 2
    Let’s break down how our PageTitle() function component is using the Effect Hook to execute some code after each render! import React, { useState, useEffect } from ‘react’; function PageTitle()…
  3. 3
    Some effects require cleanup. For example, we might want to add event listeners to some element in the DOM, beyond the JSX in our component. When we [add event listeners to the DOM](https://develop…
  4. 4
    The useEffect() function calls its first argument (the effect) after each time a component renders. We’ve learned how to return a cleanup function so that we don’t create performance issues and oth…
  5. 5
    When building software, we often start with default behaviors then modify them to improve performance. We’ve learned that the default behavior of the Effect Hook is to call the effect function afte…
  6. 6
    There are two main rules to keep in mind when using Hooks: * only call Hooks at the top level * only call Hooks from React functions As we have been practicing with the State Hook and the Effec…
  7. 7
    In older versions of React, many of the features that we use Hooks to support would have been handled by lifecycle methods in class components. While much of the functionality to end-users is the s…
  8. 8
    In this lesson, we learned how to write effects that manage timers, manipulate the DOM, and fetch data from a server. In earlier versions of React, we could only have executed this type of code in …

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo