In our coding bootcamp, as we speedran through React and sweated through our labs, our instructor would say - "If you squint, React is a lot like Java."
At first, it was just a catchy and funny phrase. 🤣 However, most recently, I revisited React while working on a personal Google Map calculator project. Days deep into it, I could start to see some of those similarities come to light.
Let’s dive into these connections and see how the foundational concepts of Java can illuminate our understanding of React. 💕
Table of Contents
1. App.jsx as the Java main Class (psvm)
Java:
In Java, the main
class serves as the entry point for the program, and it initiates the execution of the program.
For instance, you might instantiate objects of different classes and invoke their respective methods:
public class Main {
public static void main(String[] args) {
Home home = new Home();
home.render();
About about = new About();
about.show();
}
}
React:
Similarly, in a React application, the App.jsx
file plays a comparable role by orchestrating the main application flow.
Just as the main
method in Java can call multiple functions, App.jsx
is responsible for rendering all the components based on the application's routing and current state.
<Routes>
<Route exact path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
In the above React example from App.jsx
, the components rendered in the return statement mirror the process of calling methods or initializing objects in Java.
In this case, the containers <Welcome />
and <Home />
pages are rendered based on the web page URL path.
2. State Management with Hooks as Java Getters and Setters
Java:
In Java, you manage properties with variables and public getter/setter methods to get and set properties of attributes, such as a user's username.
private String username;
public String getUsername() {
return this.username;
}
public void setUserData(String username) {
this.username = username;
}
React:
React’s useState
hooks handle application state similarly to how Java uses getter
and setter
methods to manage object properties.
The useState
hook in React allows you to declare state variables that can change over time, much like Java's instance variables in a class.
const [username, setUsername] = useState("");
In the example above:
-
setUserName
serves as the setter method, allowing updates to the username. WhileuseState("")
meansusername
is initialized as an empty string, thesetUserName
updates the value.
Below we have a function handleInputChange
that detects a change in a web form to update user info and updates the value of username
to what the user inputs.
const handleInputChange = (event) => {
setUserName(event.target.value);
};
- You can think of accessing
username
as agetter
.
Whenever you reference username
in a component, you are effectively using a getter to access its value. For example, my webpage could render the username by:
<p>Welcome to our page {username}</p>
3. Containers as Java Classes
Java:
In Java, classes group related tasks and data together. They help manage how information flows in your application.
In this example, the Calculator
class handles calculations and stores the result.
public class Calculator {
private int result;
public void calculateSum(int a, int b) {
result = a + b;
}
public int getResult() {
return result;
}
}
React:
Similarly, in React, containers play a key role by connecting the application's data to the components. They handle things like fetching data from API calls and managing the app's state.
In this example, the Calculator container manages the state of the input value and the result,
const Calculator = () => {
// State variables to hold input value and the calculation result
const [inputValue, setInputValue] = useState(0);
const [result, setResult] = useState(0);
// Function to calculate the sum of two numbers
const calculateSum = (a, b) => {
setResult(a + b); // Update result state with sum
};
return (
<div>
{/* Pass the calculateSum function to the ManualFilter component */}
<ManualFilter onCalculate={calculateSum} />
<h2>Result: {result}</h2> {/* Display result of the calculation */}
</div>
);
};
export default Calculator;
4. Components as Java Methods
Java:
Methods in Java perform specific actions, such as handling user input. These methods can be invoked as needed to facilitate various functionalities in your application.
public void handleCheckboxChange(String category) {
// Logic to handle checkbox change
}
React:
Just like Java methods are small, focused tasks, React Components serve a similar purpose, acting as the fundamental building blocks of your user interface.
Each component is crafted for a specific functionality and can be reused throughout the application.
The ManualFilter
component below is solely focused on filtering options for users. It presents checkboxes that allow users to select specific categories.
This component can then be called within a UserForm
container page.
const ManualFilter = ({ onCategoryChange }) => {
const [selectedCategories, setSelectedCategories] = useState([]);
const handleCheckboxChange = (category) => {
setSelectedCategories((prev) =>
prev.includes(category) ? prev.filter((cat) => cat !== category) : [...prev, category]
);
onCategoryChange(category);
};
return (
<div>
{/* Render checklist */}
{['Category1', 'Category2', ...].map((cat) => (
<label key={cat}>
<input
type="checkbox"
checked={selectedCategories.includes(cat)}
onChange={() => handleCheckboxChange(cat)}
/>
{cat}
</label>
))}
</div>
);
};
export default ManualFilter;
5. React’s Return in Components
Java:
In Java, a method might return a value that another part of the program uses to generate output.
For example, the renderOutput
method returns a string containing the user's goal, which can then be displayed elsewhere in the program.
public String renderOutput() {
return "User Goal: " + userGoal;
}
React:
The return statement in React components is crucial for rendering the user interface. In React, what you return from a component dictates what the user sees on the screen.
This is similar to how as aforementioned, a method in Java that returns data intended for processing or display in another part of the program.
In this example, the UserGoal
component returns a paragraph element that displays the user's goal.
const UserGoal = ({ goal }) => {
return <p>User Goal: {goal}</p>;
};
6. Props as Java Method Parameters
Java:
You can passing arguments to a Java method, where the arguments can affect the state or behavior of the calling object.
For example, consider a simple Java method that takes a message as a parameter. The message it receives will affect what the console will show.
public void displayMessage(String message) {
System.out.println(message);
}
React:
In React, components can receive props, which are similar to parameters in Java methods. React components use props to determine their content and functionality.
Props control how components behave and what data they display.
Let's say we have a parent component called WelcomePage
that will pass a message to the MessageDisplay
child component.
In other words, imagine a MessageDisplay
as a section on the WelcomePage
landing page where a message shows.
We can define a message in the parent component and pass it as a prop to the MessageDisplay
component:
const WelcomePage = () => {
const greetingMessage = "Hello, welcome to my app!"; // Define a message to pass
return (
<div>
<h1>Main Application</h1>
{/* Pass the greetingMessage as a prop to MessageDisplay */}
<MessageDisplay message={greetingMessage} />
</div>
);
};
export default WelcomePage;
The MessageDisplay
component will receive this prop and render it:
const MessageDisplay = ({ message }) => {
return <h1>{message}</h1>;
};
7. Callback Functions as Java Methods that Return Values
Java:
In Java, you often have methods within classes that perform specific actions and return values to their caller. For example, you might have a class named Calculator
with a method that calculates the difference between two numbers:
public int calculateDifference(int a, int b) {
return a - b; // This method returns the result of the calculation to the caller
}
^In another class you create an instance of the Calculator
class and call that method.
React:
React follows a similar concept, but it focuses on the relationship between components.
When you have a parent component that contains child components, callback functions help facilitate communication between them. (Remember: parent is a main container that holds the other components - similar to our earlier example of a parent "landing page" with a sub-component of a message box)
For instance, let’s say you have a ChildComponent
that needs to send some calculated data back to its parent component.
Below we pass the handleCalculationResult
function from the parent to the child as a prop.
This function acts like a callback:
// Parent component
const ResultsPage = () => {
const [calculationResult, setCalculationResult] = useState(null); // State to store the calculation result
const handleCalculationResult = (result) => {
setCalculationResult(result); // Update state with the result from the child
};
return (
<div>
<ChildComponent onCalculate={handleCalculationResult} />
<h2>Calculation Result: {calculationResult}</h2>
)}
</div>
);
};
You can see below how onCalculate
is a callback function received in the ChildComponent from the parent component.
When the button in ChildComponent
is clicked, it performs the calculation and uses onCalculate
to send the result back to the parent. This mimics how Java methods return values to their callers.
const ChildComponent = ({ onCalculate }) => {
const handleCalculate = () => {
const result = 5 - 3; // Example calculation
onCalculate(result); // Calls the parent function, sending back the calculated result
};
return <button onClick={handleCalculate}>Calculate</button>; // Button triggers the calculation
};
In this way, the parent manages the overall application state and behavior while the child focuses on a specific action (in this case, the calculation).