React

Modern React From The Beginning EP7: State Management


Subscribe On YouTube

Episodes

You’ve already learned how to use props (component properties) to pass data into components. We’ve been using props to pass the array of courses into our CoursesList component. CoursesList component then makes use of the prop data to render it’s HTML output.

Another concept of managing data within your React application is State. The main difference to props is that state is managing data which is needed to render the result only within a component. For both concepts, props and state, the data is stored in plain JavaScript objects.

In this tutorial you’ll get started with state management in React. We’ll use the sample application and extend App component with state to manage the data which is provided by the user by using the search input field we’ve been added in the last episode.

Using The State Hook To Add State To Functional Components

Let’s add a new state for managing the search text data into App component by using the state hook. To be able to use this hook let’s extend the first import statement:

import React, {useState} from 'react';

So what are hooks? Hooks are functions that let you hook into React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. The hooks concepts fits perfectly into our sample application because we’ve implemented all of our components as functional components so far. The useState hook let’s us add state to functional components.

Let’s call the useState function inside of App component:

const App = () => {
  const [searchText, setSearchText] = useState('');
  ...
}

The useState function call return an array and we’re using the array destructuring syntax to extract the current state value into a variable which is called searchText and the function which needs to be used to update the state value into setSearchText.

The array destructuring syntax is very similar to the object destructuring syntax you’ve learnt about before. Instead of using curly braces you’re using brackets to pull out and assign array items at the same time.

The useState function takes one parameter: the value of the initial state. In our example we’re setting the initial state value to an empty string.

Setting The State Value

Now we’ve created a component state which is able to hold the search text data which is entered by the user. To update the state value everytime the user changes the input we’re using the handleSearchInputChange function to call the setSearchText function and pass in the new state value:

  const handleSearchInputChange = event => {
    setSearchText(event.target.value);
  }

This code ensures that the searchText state value is always up-to-date and corresponds to the value of the text input field.

Filtering The Courses Array With The State Value

In the next step we need to apply the searchText value to filter to the list of courses. This is done with the following code:

const filteredCourses = courses.filter(course => {
    return course.title.includes(searchText) || course.author.includes(searchText);
  });

To create a new filtered array we’re using the filter method of the courses array and pass in a function which returns true for every item which should remain in the new array and false for every item which should be skipped.

Using The Filtered List Of Courses

Now the filtered list of courses (filteredCourses) needs to be handed over to CoursesList component to make sure that only the list of filtered courses is displayed in the browser:

<CoursesList courses={filteredCourses} />

If you you use the search field to type in a search text in the browser you’ll see that the list is automatically filtered as you type along.

Again, here you can see the complete source code of App.js:

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

const courses = [
  {
    id: 1,
    title: "React - The Complete Guide (incl Hooks, React Router, Redux)",
    author: "Maximilian Schwarzmüller",
    hours_video: 40.5,
    number_of_lectures: 490,
    rating: 4.6,
    url: "https://codingthesmartway.com/courses/react-complete-guide/"
  },
  {
    id: 2,
    title: "Modern React with Redux",
    author: "Stephen Grider",
    hours_video: 47.5,
    number_of_lectures: 488,
    rating: 4.6,
    url: "https://codingthesmartway.com/courses/modern-react-with-redux/"
  },
  {
    id: 3,
    title: "The Complete React Developer Course (w/ Hooks and Redux)",
    author: "Andrew Mead",
    hours_video: 39,
    number_of_lectures: 200,
    rating: 4.7,
    url: "http://codingthesmartway.net/courses/complete-react-web-app-developer/"
  }
];

const App = () => {
  const [searchText, setSearchText] = useState('');

  const handleSearchInputChange = event => {
    setSearchText(event.target.value);
  }

  const filteredCourses = courses.filter(course => {
    return course.title.includes(searchText) || course.author.includes(searchText);
  });

  return (
    <div>
      <h1>List of Courses</h1>
      <hr />

      <label htmlFor="searchInput">Search: </label>
      <input  id="searchInput"
              type="text"
              onChange={handleSearchInputChange} />
      
      <CoursesList courses={filteredCourses} />
    </div>
  );
}

export default App;

What’s Next

So far we’ve added all the code which is needed to display the search input field and execute the corresponding search logic within App component. In the next step, we’re going to further structure our application by extracting a search component for those purposes.

Advertisement: Top 3 React Online Courses

If you want to dive deeper and become a React pro also consider taking one of the following great online courses.

React – The Complete Guide (incl Hooks, React Router, Redux)*
Dive in and learn React.js from scratch! Learn Reactjs, Hooks, Redux, React Routing, Animations, Next.js and way more!

Go To Course*

Modern React with Redux*
Master React v16.6.3 and Redux with React Router, Webpack, and Create-React-App. Includes Hooks!

Go To Course*

The Complete React Developer Course (w/ Hooks and Redux)*
Learn how to build and launch React web applications using React, Redux, Webpack, React-Router, and more!

Go To Course*

* Affiliate Link / Advertisement: This blog post contains affiliate links, which means that if you click on one of the product links and buy a product, we’ll receive a small commission. There are no additional costs for you. This helps support the channel and allows us to continue to make videos like this. Thank you for the support!


Using and writing about best practices and latest technologies in web design & development is my passion.