React Components
React components are very similar to JavaScript functions; they allow us to create our own
functionalities and reuse them wherever we like across our application. For example, in traditional
HTML CSS websites, you have to write codes for headers and footers repeatedly on multiple pages,
which is the same code repeated on each page you create. React offers components to be written only
once and can be called on a webpage wherever needed.
Our first-ever component is provided by React, which is App.js. Therefore, we can build our own
components for different functionalities across our web app.
What can a component return ?
• Components can return jsx elements, strings, number, booleans, null values, arrays and
fragments
• Jsx elements can only be wrapped in one parent element.
• Fragment can be used to return multiple elements, if we don’t want to add another element to
the DOM.
• Fragments can be written as <></>
• A component can return another components.
Now, let’s create a new component, Message, that alerts the screen when a button is clicked
function Message() {
const clickEvent = () => { alert(“Hello”) } return ( <div> <button onClick={ clickEvent }> Button </button> </div> ); }
export default Message;
Props in React
Props are data passed to components in JavaScript. Props are otherwise known as properties of an
object, and they are available as parameters in the components.
Example of a prop.
function App() {
return ( <Greet name=’james’/> ); }
export default App;
function Greet(props) {
return ( <div> Hello {props.name} </div> ); }
export default Greet;
The UI will change to display the new message; Hello James.
State in React
State refers to the current instance of an application. When I visit a web page, it starts in a certain initial
‘state.’ However, if I stick around and click a toggle that opens a menu, the app is in a new state where
the menu is displayed with its items. If I continue to stay on the page and click a ‘like’ button, and the
thumb turns red, that is now a new state for the app.
We manage state in a React component by using the useState function provided by React.
UseState can be called to action by importing it, just like this;
import React, { useState } from ‘react’
useState() accepts the initial value of the state item and returns an array containing the state
variable, and the function you call to alter the state.
Example

The image above depicts a function that counts from 0 when a button is clicked. The count increases by
1 as long as the button is being clicked. The initial or current state of the button is 0. Whenever the
button is clicked, this initial state gets updated and increases to a new state of 1. Now, 1 becomes the
most current state of the button until the button is clicked again. It updates its count by adding 1,
making the total new state 2 (i.e., 1 + 1 = 2).
