2. Class-based and Functional Components
Class-based components -> Used when you need to define state, lifecycle
methods.
Functional components -> Cannot define state or lifecycle methods within the
component.
3. Let’s build a React app with classes
STEP 1.
1. Prerequisites
All we need is Node and React 16.8.0 or higher.
$ npm install --save react@^16.8.0 react-dom@^16.8.0
1. Create an application
$ npx create-react-app my-app
$ cd my-app
$ npm start
4. Let’s build a React app with classes
STEP 2.
1. Create some class based and functional components.
// Todo.js (class based component)
import React, {Component} from 'react';
import Item from './Item';
class Todo extends Component {
state = {
todos: [
{text: 'Learn about React'},
{text: 'Meet friend for lunch'},
{text: 'Build really cool todo app'}
]
};
7. Let’s build a React app with classes
STEP 3.
1. Application works, great!
8. React hooks
What are React hooks?
Hooks are functions that let you use state and lifecycle method features in
functional components. They let you use React without classes.
Allows you to create every component as a functional component which is clean
and simple.
9. Classes vs react hooks/ why use React hooks
● Complex components become hard to understand
● Classes confuse both people and machines
Note:
● 100% backwards-compatible
● There are no plans to remove classes from React
● Hooks don’t replace your knowledge of React concepts
10. Syntax differences between classes and react
hooks
● useState(...) replaces state and setState(...).
● useEffect replaces lifecycle methods.
● Functions replace classes.
11. Let’s introduce React hooks into our application
STEP 1.
1. Use the useState hook.
// Todo.js
. . .
const Todo = props => {
const [todos, setTodos] = useState([
{text: 'Learn about React'},
{text: 'Meet friend for lunch'},
{text: 'Build really cool todo app'}
]);
const [showTodos, setShowTodos] = useState(false);
const handleShowTodos = () => {
setShowTodos(!showTodos);
};
15. Let’s introduce React hooks into our application
STEP 2.
1. Application works, great!
Homework
Look into how the useEffect hook is used to replace the rest of the lifecycle
methods i.e componentDidUpdate(), componentWillUnmount(),
shouldComponentUpdate() and getDerivedStateFromProps().