Declarative UI in React JS
1. Introduction to Declarative UI
Declarative UI is a programming approach in which developers describe what the user interface should look like for a particular application state instead of manually specifying every step required to update the interface. React follows this approach by allowing developers to build interfaces using components, JSX, props, and state.
When the application data changes, React renders the component again and determines whether the actual DOM needs to be updated. This approach makes user interface development easier to understand, maintain, and scale.
2. Definition of Declarative UI
Declarative UI means describing the expected appearance of an interface based on the current data and state. React manages the rendering process and applies the necessary DOM updates.
For example, instead of manually finding a heading and changing its text whenever a username changes, a developer can display the username directly through JSX.
Example
function Welcome() {
const username = "Rahul";
return (
<div>
<h1>Welcome, {username}!</h1>
<p>Welcome to React JS.</p>
</div>
);
}
export default Welcome;
Output: The page displays "Welcome, Rahul!" and "Welcome to React JS."
Explanation: The developer describes the desired interface using JSX. React takes care of rendering the component.
3. How Declarative UI Works in React
Declarative UI connects application data with the visual interface. When relevant props or state change, React renders the component again and determines what changes are necessary.
- Create a component: Write a JavaScript function that returns JSX.
- Describe the interface: Define the elements that should appear on the screen.
- Provide data: Use props, state, or other appropriate data sources.
- Handle user interactions: Update state when users click buttons, enter text, or submit forms.
- Render the updated interface: React determines the required updates to the DOM.
Example: Changing a Message
import { useState } from "react";
function MessageApp() {
const [message, setMessage] = useState("Hello, User!");
return (
<div>
<h2>{message}</h2>
<button onClick={() => setMessage("Welcome to React!")}>
Change Message
</button>
</div>
);
}
export default MessageApp;
Explanation: Initially, the heading displays "Hello, User!". When the button is clicked, the message state changes. React renders the updated heading without requiring the developer to manually modify the DOM.
4. Declarative UI vs. Imperative UI
Declarative and imperative UI are two different approaches to describing how an interface should behave.
| Basis |
Declarative UI |
Imperative UI |
| Meaning |
Describes what the UI should display. |
Describes the steps needed to change the UI. |
| Approach |
State-driven rendering. |
Step-by-step instructions. |
| DOM handling |
React manages ordinary DOM updates. |
Developers often manipulate DOM elements directly. |
| Code readability |
Often easier to understand and maintain. |
Can become complex when many manual updates are required. |
| Example |
Rendering a heading using JSX and state. |
Finding an element and assigning its text manually. |
| Common usage |
React components and state-driven interfaces. |
Direct DOM manipulation and step-by-step operations. |
Imperative Example Using JavaScript
const heading = document.getElementById("title");
heading.textContent = "Welcome to React!";
This example directly finds an HTML element and changes its text. The developer specifies the exact operation to perform.
Declarative Example Using React
import { useState } from "react";
function App() {
const [title, setTitle] = useState("Hello");
return (
<div>
<h1>{title}</h1>
<button onClick={() => setTitle("Welcome to React!")}>
Update Title
</button>
</div>
);
}
export default App;
Here, the heading is determined by the title state. When the state changes, React renders the updated interface. Imperative code is not always wrong, but declarative rendering is generally preferred for normal React UI updates.
5. Role of JSX in Declarative UI
JSX is a JavaScript syntax extension that allows developers to write HTML-like markup inside JavaScript code. It is commonly used to describe the structure of React interfaces.
JSX can display static content, JavaScript expressions, component output, and data from props or state.
Example
function Product() {
const productName = "Laptop";
const price = 55000;
return (
<div>
<h2>{productName}</h2>
<p>Price: ₹{price}</p>
</div>
);
}
export default Product;
Explanation: The product name and price are displayed through JSX expressions. When such values come from props or state, the UI can reflect changes to the application data.
6. Role of Components
Components are reusable building blocks of React applications. A component can represent a small element, such as a button, or a complete section, such as a navigation bar, product card, login form, or footer.
Developers can combine smaller components to create larger interfaces. This makes applications easier to organize and maintain.
Example
function Header() {
return <h1>My Online Store</h1>;
}
function ProductCard() {
return (
<div>
<h2>Wireless Headphones</h2>
<p>Price: ₹1,999</p>
</div>
);
}
function App() {
return (
<div>
<Header />
<ProductCard />
</div>
);
}
export default App;
The Header and ProductCard components describe separate parts of the page. The App component combines them into one interface.
7. Role of Props in Declarative UI
Props are inputs passed from a parent component to a child component. They allow developers to reuse the same component with different data.
Example
function Greeting({ name }) {
return <h2>Hello, {name}!</h2>;
}
function App() {
return (
<div>
<Greeting name="Amit" />
<Greeting name="Priya" />
</div>
);
}
export default App;
Output: The page displays "Hello, Amit!" and "Hello, Priya!". Both greetings use the same component with different props.
Props should be treated as read-only inputs. If data needs to change through user interaction, the component can use state or request an update from its parent.
8. Role of State in Declarative UI
State stores information that can change over time and affect what a component displays. React's useState Hook is commonly used to manage state in functional components.
Example: Counter Application
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
Explanation: The counter starts at zero. Each button click requests a state update, and React renders the new count. The displayed number is determined by the current state.
9. Conditional Rendering
Conditional rendering means displaying different UI elements according to a condition. React supports JavaScript if statements, the logical AND operator, and the ternary operator for conditional rendering.
Example: Login Status
function LoginStatus({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<h2>Welcome Back!</h2>
) : (
<h2>Please Log In</h2>
)}
</div>
);
}
export default LoginStatus;
When isLoggedIn is true, the component displays "Welcome Back!". Otherwise, it displays "Please Log In". The interface depends on the supplied prop.
10. Declarative UI and Event Handling
Event handling allows React components to respond to actions such as clicking buttons, typing into input fields, submitting forms, and selecting options. Event handlers can update state, which then determines the rendered interface.
Example: Show or Hide a Message
import { useState } from "react";
function ToggleMessage() {
const [visible, setVisible] = useState(false);
return (
<div>
<button onClick={() => setVisible(!visible)}>
Toggle Message
</button>
{visible && <p>This message is now visible.</p>}
</div>
);
}
export default ToggleMessage;
Initially, the message is hidden. Clicking the button changes the visible state. React then displays or removes the paragraph according to the new state.
11. Declarative UI in Forms
Forms often have different visual states, such as empty, typing, submitting, successful, or failed. React can represent these states and display the appropriate interface for each one.
Example: Controlled Input
import { useState } from "react";
function NameForm() {
const [name, setName] = useState("");
return (
<div>
<label htmlFor="username">Enter your name:</label>
<input
id="username"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<p>Your name: {name || "Not entered"}</p>
</div>
);
}
export default NameForm;
The input value is controlled by React state. As the user types, the onChange event updates the name state, and the paragraph displays the latest value.
12. Benefits of Declarative UI
- Readable code: The component structure communicates the intended interface.
- Maintainability: UI logic can be organized into smaller components.
- Predictable rendering: The interface is described using current props and state.
- Reusability: Components can display different information through props.
- Reduced manual DOM manipulation: React manages normal interface updates.
- Conditional interfaces: Different application states can be represented clearly.
- Testability: Components can be tested with different inputs and states.
- Scalability: Component-based development helps organize larger applications.
- Easier debugging: Developers can inspect the state and props that determine the UI.
13. Best Practices for Declarative UI
- Divide large interfaces into small, reusable components.
- Use props to pass information from parent components to child components.
- Use state for information that changes over time and affects rendering.
- Avoid unnecessary direct DOM manipulation when React rendering can handle the update.
- Keep rendering logic pure and avoid side effects during rendering.
- Do not mutate state objects or arrays directly; create updated values instead.
- Use meaningful component and variable names.
- Represent loading, success, error, and empty states clearly.
- Avoid storing duplicate state when a value can be calculated from existing data.
- Follow the Rules of Hooks and call Hooks at the top level of React components or custom Hooks.
- Use stable keys when rendering lists of elements.
- Test different states and user interactions.
14. Common Mistakes in Declarative UI
| Mistake |
Problem |
Recommended Approach |
| Direct DOM manipulation |
Manual changes can conflict with React's rendering. |
Represent the UI through JSX and state. |
| Direct state mutation |
React may not recognize the intended update. |
Use the state setter with a new value. |
| Large components |
Code becomes difficult to maintain. |
Split the interface into focused components. |
| Changing props directly |
Props are read-only inputs. |
Use state or parent-managed updates. |
| Duplicate state |
Values can become inconsistent. |
Calculate derived values when possible. |
| Ignoring error states |
Users may not understand application failures. |
Render appropriate error and recovery messages. |
15. Practical Project: Declarative Task List
A task list demonstrates how to use state, controlled inputs, event handlers, and list rendering to build an interactive interface.
Complete Example
import { useState } from "react";
function TaskList() {
const [task, setTask] = useState("");
const [tasks, setTasks] = useState([]);
function addTask() {
const trimmedTask = task.trim();
if (trimmedTask === "") return;
setTasks((previousTasks) => [
...previousTasks,
{ id: crypto.randomUUID(), text: trimmedTask }
]);
setTask("");
}
return (
<div>
<h1>My Task List</h1>
<input
value={task}
onChange={(event) => setTask(event.target.value)}
placeholder="Enter a task"
/>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
</div>
);
}
export default TaskList;
Project Explanation
- The task state stores the current input value.
- The tasks state stores the list of tasks.
- The onChange event updates the input state.
- The Add Task button adds a task through the state setter.
- The map() method converts the task data into list elements.
- Each task has a stable identifier used as its React key.
- React renders the updated list when the state changes.
Expected result: Users can enter a task and click Add Task to display it in the list. This example does not include deletion, task completion, or permanent storage; those features can be added as further exercises.
16. Real-World Applications of Declarative UI
- E-commerce websites: Displaying products, prices, shopping carts, and order statuses.
- Dashboards: Updating statistics, charts, and notifications.
- Authentication systems: Showing login forms and account information.
- Social media: Rendering posts, comments, reactions, and user profiles.
- Task management: Displaying task lists, completion status, and filters.
- Booking systems: Showing availability, form validation, and booking confirmations.
- Educational platforms: Displaying lessons, quizzes, and student progress.
17. Interview Questions and Answers
Q1. What is Declarative UI in React?
Answer: Declarative UI is an approach in which developers describe what the interface should display based on the current props and state. React manages rendering and necessary DOM updates.
Q2. How does declarative UI differ from imperative UI?
Answer: Declarative UI describes the desired result, whereas imperative UI specifies the steps required to achieve that result.
Q3. What is the role of state in declarative UI?
Answer: State stores information that can change over time and influence what a component displays. Updating state can trigger a re-render.
Q4. Why is JSX useful?
Answer: JSX provides an HTML-like syntax for describing UI elements inside JavaScript and supports dynamic expressions.
Q5. What is conditional rendering?
Answer: Conditional rendering means displaying UI elements according to a condition using JavaScript expressions such as the ternary operator or logical AND.
Q6. Why should unnecessary DOM manipulation be avoided in React?
Answer: Manual DOM changes can become inconsistent with React's rendering model. Using state and JSX generally keeps the displayed interface aligned with application data.
Q7. Can declarative UI be used for forms?
Answer: Yes. React can use state to represent input values, validation messages, submission progress, and success or error states.
Q8. Does declarative UI mean developers never write imperative code?
Answer: No. Imperative code is still useful for tasks such as focusing an input, interacting with browser APIs, and integrating third-party libraries. Declarative rendering is generally preferred for describing the UI.
18. Practice Exercises
- Create a counter with Increase and Decrease buttons.
- Build a login component that displays different messages according to login status.
- Create a product card that accepts a name and price through props.
- Build a toggle button that shows and hides a paragraph.
- Create a controlled input that displays entered text in real time.
- Build a task list that supports adding and deleting tasks.
- Create a loading component that switches to success or error content based on state.
- Build a shopping cart that updates its item count when products are added.
19. Conclusion
Declarative UI is a fundamental concept in React JS. It allows developers to describe the expected interface using components, JSX, props, and state instead of manually managing every DOM update. Understanding declarative UI helps developers create interactive, reusable, readable, and maintainable web applications.
Practise counters, forms, conditional interfaces, product cards, and task lists to understand how React state and rendering work together.
20. Learn React JS with JustAcademy
Explore the React JS Training Course to continue learning React fundamentals, JSX, components, state management, and practical application development.
JustAcademy React JS Training Course
To learn more about the training, you can also register for a course demonstration using the link below.
Register for React JS Course Demo