React Fundamentals Refresher
9 min read
React Fundamentals Refresher ⚛️
Welcome back to your React Native journey! Before we dive deep into building stunning mobile apps, let's refresh our memory on the fundamental concepts of React. These are the absolute essentials, the bread and butter of any React or React Native developer. Mastering these will make your development experience smoother and way more fun. Let's get started!
1. Components: The Building Blocks of Mobile UI 🧱
The Problem: Imagine building a complex user interface, like a social media feed. You have posts, comments, like buttons, user profiles, and so on. If you were to write the code for this entire screen in one single, massive file, it would quickly become a nightmare to manage, debug, and update. How can we break this complexity into smaller, manageable, and reusable pieces?
The Solution: Components
In React, we build user interfaces by breaking them down into smaller, independent, and reusable pieces called components. Think of them like Lego bricks. You can build a small car, a house, or a giant castle by combining different Lego bricks. Similarly, you can build a simple button, a complex form, or an entire screen by combining different components.
Each component has its own logic and appearance. For example, a LikeButton component would have the logic to handle a press and the appearance of a thumbs-up icon.
Types of Components:
In the world of React, there are two main types of components:
Functional Components: These are the modern and recommended way of writing components. They are simple JavaScript functions that accept
props(more on this later) as an argument and return a React element that describes what should be rendered on the screen.javascriptimport React from 'react'; import { Text, View } from 'react-native'; const Greeting = (props) => { return ( <View> <Text>Hello, {props.name}!</Text> </View> ); }; export default Greeting;Class Components: These are the original way of writing components. They are ES6 classes that extend from
React.Componentand have arender()method that returns a React element. While you might still encounter them in older codebases, functional components with Hooks (likeuseState) are the standard for new development.javascriptimport React, { Component } from 'react'; import { Text, View } from 'react-native'; class Greeting extends Component { render() { return ( <View> <Text>Hello, {this.props.name}!</Text> </View> ); } } export default Greeting;
Why are components so cool?
- Reusability: You can write a component once and use it in multiple places in your application. For example, a custom
Buttoncomponent can be used on every screen of your app. - Separation of Concerns: Each component manages its own state and logic, making your code easier to understand and maintain.
- Composability: You can build complex UIs by combining smaller, simpler components.
✨ Fun Fact: The concept of component-based architecture was popularized by React, but it was inspired by earlier technologies like XAML used in Windows development and Web Components.
2. JSX: Writing UI like a Pro ✍️
The Problem: In traditional web development, you often have separate HTML, CSS, and JavaScript files. This separation can become cumbersome as your application grows, and you find yourself jumping between files to understand how a piece of the UI works. Wouldn't it be great if you could write your UI structure and logic in the same place?
The Solution: JSX
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code directly within your JavaScript files. It's not HTML, but it looks very similar. This makes it incredibly intuitive to describe what your UI should look like.
Here's a little secret: browsers and mobile devices don't actually understand JSX. Before your code is executed, a tool called a transpiler (like Babel) converts your JSX code into regular React.createElement() function calls, which JavaScript can understand.
Let's see it in action:
This is what you write (JSX):
const element = <Text>Hello, world!</Text>;This is what Babel turns it into:
const element = React.createElement(Text, null, 'Hello, world!');See? You get to write clean, declarative UI code, and the tools handle the rest. It's like having a personal assistant who translates your brilliant ideas into the language the machine understands.
Key Features of JSX:
Expressions in Braces: You can embed any JavaScript expression within curly braces
{}inside JSX.javascriptconst name = 'John Doe'; const element = <Text>Hello, {name}</Text>;Attributes: You can specify attributes for your elements, similar to HTML. In React Native, these are called
props. Notice the use ofcamelCasefor styling properties likefontSize.javascriptimport React from 'react'; import { Text, View, StyleSheet } from 'react-native'; const App = () => ( <View style={styles.container}> <Text style={{ fontSize: 24 }}>Hello, JSX!</Text> </View> ); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', } }) export default App;One Root Element: A component can only return a single root element. If you need to return multiple elements, you can wrap them in a
Viewor aFragment(<>...</>).javascript// Correct ✅ const UserInfo = () => ( <View> <Text>Name: John Doe</Text> <Text>Age: 30</Text> </View> ); // Incorrect ❌ /* const UserInfo = () => ( <Text>Name: John Doe</Text> <Text>Age: 30</Text> ); */
Imagine a world without JSX. You'd be writing React.createElement('View', null, React.createElement('Text', null, 'Hello')) for every single piece of your UI. We would all be living in a nested parenthesis nightmare! 😂
3. Props: Passing Data Between Components 🎁
The Problem: You've built these nice, isolated components. But how do you make them talk to each other? How does a UserProfile component know which user's information to display? You need a way to pass data from a parent component to a child component.
The Solution: Props
Props (short for properties) are how you pass data from a parent component to a child component. Props are read-only, which means a child component should never modify the props it receives. This ensures a predictable, one-way data flow.
Think of it like this: You're building a house (the parent component) and you hire a painter (the child component). You tell the painter, "I want the walls to be blue." The color "blue" is a prop you are passing to the painter. The painter's job is to use that color, not to decide to paint the walls red instead.
How to Use Props:
Passing Props from Parent to Child:
In the parent component, you add props to the child component as if they were HTML attributes.
javascriptimport React from 'react'; import { View } from 'react-native'; import Greeting from './Greeting'; // Assuming Greeting component is in a separate file const App = () => { return ( <View> <Greeting name="Alice" /> <Greeting name="Bob" /> </View> ); }; export default App;Receiving Props in the Child Component:
The child component receives the props as an argument to the function.
javascriptimport React from 'react'; import { Text } from 'react-native'; const Greeting = (props) => { return <Text>Hello, {props.name}!</Text>; }; export default Greeting;
Industry Practice: Destructuring Props
To make your code cleaner, it's a common practice to destructure the props object right in the function's signature.
// Instead of this:
// const Greeting = (props) => {
// return <Text>Hello, {props.name}!</Text>;
// };
// Do this:
const Greeting = ({ name }) => {
return <Text>Hello, {name}!</Text>;
};This makes it immediately clear what props the component expects to receive.
4. State (useState): Making Your App Interactive ❤️🔥
The Problem: Your app looks great, but it's static. It doesn't respond to user input. How do you make a button that actually does something when you press it? How do you handle data that changes over time, like a user typing into a text field or a list of items being updated?
The Solution: State and the useState Hook
State is data that a component can hold and manage. Unlike props, which are passed from the outside, a component's state is private and controlled by the component itself. The magic of state is that whenever the state changes, React will automatically re-render the component to reflect those changes.
The useState hook is a special function that lets you add state to your functional components.
How to Use useState:
Let's build a simple counter to understand how it works.
Import
useStatefrom React:javascriptimport React, { useState } from 'react';Initialize State:
Call
useStateat the top level of your component to declare a state variable.useStatereturns an array with two elements:- The current state value.
- A function to update that state value.
We use array destructuring to get these two values.
javascriptconst [count, setCount] = useState(0); // 0 is the initial stateHere,
countis our state variable, andsetCountis the function we'll use to update it. We've initializedcountto0.Read and Display the State:
You can use the
countvariable directly in your JSX.javascript<Text>You clicked {count} times</Text>Update the State:
Call the
setCountfunction to update the state. This is typically done in an event handler, like theonPressof a button.javascript<Button title="Click me" onPress={() => setCount(count + 1)} />
Putting It All Together: The Counter Component
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<View style={styles.container}>
<Text style={styles.text}>You clicked {count} times</Text>
<Button
title="Click me"
onPress={() => setCount(count + 1)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
alignItems: 'center',
margin: 20,
},
text: {
fontSize: 18,
marginBottom: 10,
}
})
export default Counter;Every time you press the button, setCount(count + 1) is called. This updates the count state, and React re-renders the Counter component, displaying the new count on the screen. It's like a little bit of magic! ✨
Trying to manage interactivity without something like useState would be like trying to remember everyone's order in a busy restaurant without writing anything down. You'd be guaranteed to mess things up and deliver a cold (and wrong) meal to your users!
Further Reading & References 📚
- React Official Documentation:
- React Native Official Documentation:
Challenge
Your Task
Create a dynamic UserProfile component in React that displays user information and allows toggling the visibility of the user's email address.
Requirements
Create a
UserProfileFunctional Component:- It must accept an object of
propscontainingname,username, andemail. - Inside the component, use the
useStatehook to create a state variable calledisEmailVisible, initialized tofalse. - It should render the user's
nameandusernameat all times. - It must conditionally render the user's
email. The email should only be visible whenisEmailVisibleistrue. - Include a
Buttoncomponent with the title "Show/Hide Email". When this button is pressed, it should toggle theisEmailVisiblestate.
- It must accept an object of
Create a Root
AppComponent:- This component will act as the parent.
- It should render your
UserProfilecomponent. - Pass the following user data as props to
UserProfile:{ name: 'Jane Doe', username: 'janedoe99', email: '[email protected]' }.
Expected result
Your code should define two functional components: UserProfile and App.
The UserProfile component should correctly destructure name, username, and email from its props. It must initialize a state variable isEmailVisible using useState(false). The component's return statement should use JSX to display the name and username, and conditionally render the email based on the isEmailVisible state. A button's onPress handler should call the state update function to toggle the boolean value.
The App component should simply render the UserProfile component, passing the required user data as props.
Example Implementation:
const UserProfile = ({ name, username, email }) => {
const [isEmailVisible, setIsEmailVisible] = useState(false);
const toggleEmailVisibility = () => {
setIsEmailVisible(!isEmailVisible);
};
return (
<View>
<Text>Name: {name}</Text>
<Text>Username: {username}</Text>
{isEmailVisible && <Text>Email: {email}</Text>}
<Button onPress={toggleEmailVisibility} title="Show/Hide Email" />
</View>
);
};
const App = () => {
const userData = {
name: 'Jane Doe',
username: 'janedoe99',
email: '[email protected]'
};
return (
<UserProfile
name={userData.name}
username={userData.username}
email={userData.email}
/>
);
};