SEI-Example
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Unidirectional Data Flow
  • What is Unidirectional Data Flow?
  • We do: Build a Fruit Filter 🫐
  • Child Components
  • Container Component
  • Finished Child components:
  • You do: Also display the fruits that do not match the filter
  • Solution - Unmatching Filter
  • Final Thoughts
  1. React (Updated 2019)
  2. React State

Lifting State

PreviousLab: Simple CalcNextReact Router

Last updated 3 years ago

Unidirectional Data Flow

Learning Objectives

After this lesson, you will be able to:

  • Define unidirectional flow

  • Diagram data in a component hierarchy

What is Unidirectional Data Flow?

Let's start with .

In React applications, data usually flows from the top down. Why do we care? How does this apply?

When several components in a view need to share state, you lift, or hoist, the state so that it's available to all the components that need it. Define the state in the highest component you can, so that you can pass it to any components which will need it. Let's look at a search filter as an example. This app will have two basic components - one that displays a list of data, and one that captures user input to filter the data.

We do: Build a Fruit Filter 🫐

Our data will be simple - a list of fruits. The app will end up looking something like this:

When building a React app, it's important to take time to define the app's structure before you start writing code. We're going to define the components and the state we need before we write the code.

Components

This app needs two components:

  • A List component to display the list of fruit.

    • This component needs one piece of data: the array of fruits to display.

  • An Input to capture the filter value from the user.

    • This component needs one piece of data: the current value of the filter.

State

This app needs to keep track of changes in two items:

  • The filtered list of fruits

  • The value of the filter

Component hierarchy

We have two sibling components (components at the same level of the tree/app) that need to be aware of each other's data. Specifically, the List component needs to only show the fruits that match the filter value. So we need to get data from one sibling to another. Something like this:

How to achieve this, though? Using unidrectional data flow, of course! If we create a container component to hold both the filter value and the filtered list, we can hoist the state to the container so it's available to all the children. It will then be simple to display the state in the child components. The data will flow like this:

Now that we know the components we need, the state we need, and where everything needs to be, we can start writing some code.

Child Components

List.js

import React from 'react';

const List = props => {

  return(
    <ul>
    {/* list will go here */}
    </ul>
  )
}

export default List;

Input.js

import React from 'react';

const Input = props => {

  return(
    <div>
        <label htmlFor="fruit-filter">Filter these Fruits: </label>
        <input type="text" name="fruit-filter" />
    </div>
  )
}

export default Input

Container Component

Our container will be a component with a few functions we'll use to initialize and update the state of the two child components. Using hooks, we'll initialize the state:

import React, {useState} from 'react';

const FruitContainer = props => {
  const [fruitsToDisplay, setFruitsToDisplay] = useState(props.fruits);
  const [filterValue, setFilterValue] = useState('');

  return(
    //...
  )
}

export default FruitContainer;

We've set up state to accept a list of fruits as props from a parent component, so let's go into App.js and make sure everything's set up the way we need it there.

import './App.css';
import FruitContainer from './FruitContainer'

function App() {
  const fruitArr = ['Apple', 'Banana', 'Grapes', 'Kiwi', 'Pineapple', 'Dragonfruit', 'Mango']
  return (
    <div className="App">
      <FruitContainer fruits={fruitArr} />
    </div>
  );
}

export default App;

We'll need a function to update the state when the filter value changes. This function will store the filter state, and filter the list of fruits to display. We'll pass this change handler to the input component to react to user behavior.

 const handleFilterChange = e => {
    e.preventDefault();

    const newValue = e.target.value;
    setFilterValue(newValue);

    // remove fruits that don't contain the filter value
    const filteredFruitList = props.fruits.filter(fruit => {
      return fruit.toLowerCase().includes(newValue.toLowerCase());
    })
    
    setFruitsToDisplay(filteredFruitList);
  }

And finally, we need to render our child components.

return (
    <div>
      <Input value={filterValue} onChange={handleFilterChange} />
      <List fruits={fruitsToDisplay} />
    </div>
  )

The full container component looks like this:

import React, {useState} from 'react';
import Input from './Input';
import List from './List';

const FruitContainer = props => {
  // Initialize the fruit list to the array passed in props
  const [fruitsToDisplay, setFruitsToDisplay] = useState(props.fruits); 
  // Initialize the filter value to an empty string
  const [filterValue, setFilterValue] = useState('');

  const handleFilterChange = e => {
    e.preventDefault();

    const newValue = e.target.value;
    setFilterValue(newValue);

    // remove fruits that don't contain the filter value
    const filteredFruitList = props.fruits.filter(fruit => {
      return fruit.toLowerCase().includes(newValue.toLowerCase());
    })
    
    setFruitsToDisplay(filteredFruitList);
  }

  return (
    <div>
      <Input value={filterValue} onChange={handleFilterChange} />
      <List fruits={fruitsToDisplay} />
    </div>
  )
}

export default FruitContainer;

All of the data is hoisted to the top of the tree in the container, and we pass it to the child components.

Now we need to return to the children components and add the functionality to handle the data they're receiving!

Finished Child components:

Input.js

import React from 'react';

const Input = props => {

  return (
    <div>
      <label htmlFor="fruit-filter">Filter these Fruits: </label>
      <input type="text" name="fruit-filter" value={props.value} onChange={props.onChange} />
    </div>
  )
}

export default Input;

List.js

import React from 'react';

const List = props => {
  const fruitItems = props.fruits.map((fruit, idx) => {
    return <li key={idx}>{fruit}</li>
  })

  return (
    <ul>
      {fruitItems}
    </ul>
  )
}

export default List;

You do: Also display the fruits that do not match the filter

  • Add another child component to the

    FruitContainer that displays the fruits that do not match the filter value

    (this should be all the items that are not in the fruitsToDisplay list).

Hint: Will you need to have a new state?

Solution - Unmatching Filter

Coming Soon!

Final Thoughts

It's important that you think through your applications before you start writing code. It's often helpful to sketch out your app, and identify:

  • the components you will need

  • the states you will need

  • where those states need to live

Use the unidirectional data flow pattern - hoist your state toward the top of the component tree so it's available to the children that need it.

a video explaining this concept.
Fruit filter app
basic data flow needed
unidirectional approach