React Tutorial — Learn React in 5 hours — Part 3
Education

As we already discussed briefly about function component in the previous section of React Tutorial . Now we are discussing in detail about Function component.
With the addition of Hooks, React’s Function components are almost as powerful as its Class components, with the difference that you probably won’t need to use a Class component.
Class components are not being removed from React at the moment, even though Function components are preferred.
Create a Function Component
Class components return HTML and behave just like functional components, but function components require much less code and are easier to understand.
Example:
Create a Function component called Bikefunction Bike() {
return <h2>Hi, I am a Bike!</h2>;
}
The Bike component in your React application returns a <h2> element. To use this component in your React application, use the following syntax:
<Bike />
Example:
Display the Bike component in the "root" element:ReactDOM.render(<Bike />, document.getElementById('root'));
Output:

Props
You can pass components as props, which stands for properties.
You send props into a component as attributes, much like function arguments.
You’ll learn more about props in the next chapter.
Example:
Use an attribute to pass a color to the Bike component, and use it in the render() function:function Bike(props) {
return <h2>I am a {props.color} Bike!</h2>;
}ReactDOM.render(<Bike color="black"/>, document.getElementById('root'));
Output:

Components in Components
Components within other components are described as follows:
Example:
Use the Bike component inside the Garage component:function Bike() {
return <h2>I am a Bike!</h2>;
}function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Bike />
</>
);
}ReactDOM.render(<Garage />, document.getElementById('root'));
Output:

Components in Files
The goal of React is to reuse code, so it is recommended to divide your components into separate files.
To do that, create a new .js file and paste the code inside:
It is important that the filename begins with a capital letter.
Example:
This is the new file, we named it "Bike.js":function Bike() {
return <h2>Hi, I am a Bike!</h2>;
}export default Bike;
You have to import the file into your application in order to use the Bike component.
Example:
After importing the "Bike.js" file, we can use the Bike component as though it were created here.import React from 'react';
import ReactDOM from 'react-dom';
import Bike from './Bike.js';ReactDOM.render(<Bike />, document.getElementById('root'));
Output:

React Hooks
Hooks were added to React in version 16.8.
While hooks generally replace class components, React does not plan to remove classes.
What is a Hook?
Hooks allow us to access React features such as state and lifecycle methods.
Example:
The following is an example of a Hook.If it does not make sense, don't worry about it. We'll explain it more in this section..import React, { useState } from "react";
import ReactDOM from "react-dom";function FavoriteColor() {
const [color, setColor] = useState("yellow");
return (
<>
<h1>My favorite color is {color}!</h1>
<button
type="button"
onClick={() => setColor("blue")}
>Blue</button>
<button
type="button"
onClick={() => setColor("yellow")}
>Yellow</button>
<button
type="button"
onClick={() => setColor("black")}
>Black</button>
<button
type="button"
onClick={() => setColor("purple")}
>Purple</button>
</>
);
}ReactDOM.render(<FavoriteColor />, document.getElementById('root'));
Output:

From React, you must import Hooks.
To keep track of application state, we are using the useState Hook.
Generally, state refers to application data or properties that need to be tracked.
Hook Rules
There are 3 rules for hooks:
- Hooks can only be called inside React function components.
- Hooks can only be called at the top level of a component.
- Hooks cannot be conditional
Note: React class components do not support hooks.
React useState Hook
UseState hooks in React allow us to track state in a function component.
Generally, a state refers to data or properties that an application needs to track.
Import useState
We first need to import the useState Hook into our component.
Example:
At the top of your component, import the useState Hook.import { useState } from "react";
It is important to note that we are destroying useState from react since it is a named export.
Initialize useState
Using useState in our function component, we initialize our state.
The useState function returns two values based on the initial state:
- The current state.
- A function that updates the state.
Example:
The function component should be initialized at the top.import { useState } from "react";function FavoriteColor() {
const [color, setColor] = useState("");
}
Again, the values returned from useState are being destructed.Our current state is represented by the first value, color.Using setColor as the second value, we can update our state.
Variables can be named anything you like.
Lastly, we set the initial state to an empty string: useState(“”)
Read State
In our component, we can now include our state anywhere.
Example:
In the rendered component, use the state variable.import { useState } from "react";
import ReactDOM from "react-dom";function FavoriteColor() {
const [color, setColor] = useState("yellow");
return <h1>My favorite color is {color}!</h1>
}ReactDOM.render(<FavoriteColor />, document.getElementById('root'));
Output:

Update State
We update our state using our state updater function.
We should never directly update state. Ex: color = “yellow” is not allowed.
Example:
Use a button to update the state:import { useState } from "react";
import ReactDOM from "react-dom";function FavoriteColor() {
const [color, setColor] = useState("yellow");
return (
<>
<h1>My favorite color is {color}!</h1>
<button
type="button"
onClick={() => setColor("red")}
>Red</button>
</>
)
}ReactDOM.render(<FavoriteColor />, document.getElementById('root'));
Output:

What Can State Hold
Use the useState Hook to keep track of strings, numbers, booleans, arrays, objects, and any combination of these!
To track individual values, we could create multiple state hooks.
Example:
Create multiple state Hooks:import { useState } from "react";
import ReactDOM from "react-dom";function Bike() {
const [brand, setBrand] = useState("BMW");
const [model, setModel] = useState("BMW R nineT");
const [year, setYear] = useState("1960");
const [color, setColor] = useState("black"); return (
<>
<h1>My {brand}</h1>
<p>
It is a {color} {model} from {year}.
</p>
</>
)
}ReactDOM.render(<Bike />, document.getElementById('root'));
Output:

We can also use an object instead of a state!
Example:
Create a single Hook that holds an object:import { useState } from "react";
import ReactDOM from "react-dom";function Bike() {
const [bike, setBike] = useState({
brand: "BMW",
model: "BMW R nineT",
year: "1960",
color: "black"
}); return (
<>
<h1>My {bike.brand}</h1>
<p>
It is a {bike.color} {bike.model} from {bike.year}.
</p>
</>
)
}ReactDOM.render(<Bike />, document.getElementById('root'));
Output:

As a result, since we are tracking one object, we must reference that object and then the property of that object in order to render the component. (Ex: bike.brand)
Updating Objects and Arrays in State
When state is updated, the entire state is overwritten.
Would it be possible to update our bike’s color only?
The setBike([color: “blue”]) function would remove the bike model, year, and brand from our state.
JavaScript’s spread operator can be used to help us.
Example:
Use the JavaScript spread operator to update only the color of the bike:import { useState } from "react";
import ReactDOM from "react-dom";function Bike() {
const [bike, setBike] = useState({
brand: "BMW",
model: "BMW R nineT",
year: "1960",
color: "black"
}); const updateColor = () => {
setBike(previousState => {
return { ...previousState, color: "blue" }
});
} return (
<>
<h1>My {bike.brand}</h1>
<p>
It is a {bike.color} {bike.model} from {bike.year}.
</p>
<button
type="button"
onClick={updateColor}
>Blue</button>
</>
)
}ReactDOM.render(<Bike />, document.getElementById('root'));
Output:

In order to get the current value of state, we pass a function to our setBike function. The function receives the previous value.
In the next step, we return an object that spreads previousState and overwrites only the color.
To read more about publications and learn, see this article.