Education
Software Development Executive - I
Last updated on Oct 24, 2023
Last updated on Aug 28, 2023
As a developer, I have always found handling events in React to be an intriguing topic. React events are the backbone of any React application, and understanding them is crucial for building interactive user interfaces. In this blog, I will delve into the advanced concepts of handling events in React, focusing on event handlers, synthetic events, and the intricacies of event handling in both class and functional components.
React events are named using camelCase, rather than lowercase, and with JSX you pass a function as the event handler, rather than a string. For example, the HTML onclick event becomes onClick in React.
1<button onClick={myFunction}>Click me</button>
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For instance, if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box.
React events are the "named callbacks" that React DOM components provide. They are triggered by user interactions or system updates, such as mouse clicks, key presses, form submissions, or even API calls.
An event handler is a function in a computer program that waits for a specific event to occur and then triggers a program routine when that event occurs. A routine is also referred to as an event handler function. In React, an event handler function is a function that gets triggered by the specified event and can access the event's properties through an event object.
1 function handleClick(event) { 2 console.log('The button was clicked'); 3 } 4
In the above example, handleClick is an event handler function that logs a message to the console when the event occurs.
React supports a variety of event types, including:
Each of these events in React has a set of associated event handlers. For instance, the onClick event handler is used to handle click events, the onChange event handler is used to handle change events, and so on.
1 function App() { 2 return ( 3 <button onClick={() => console.log('Button clicked')}> 4 Click me 5 </button> 6 ); 7 } 8 export default App; 9
In the above example, an inline arrow function is used as the onClick event handler to log a message to the console when the button is clicked.
In React, event handlers are written inside curly braces and are assigned to event attributes of React elements. The event attributes are named using camelCase, and the value of the event attribute is set to a function reference (not a function call) that handles the event.
1 function App() { 2 function handleClick() { 3 console.log('Button clicked'); 4 } 5 6 return ( 7 <button onClick={handleClick}> 8 Click me 9 </button> 10 ); 11 } 12 13 export default App; 14
In the above example, the handleClick function is an event handler function that logs a message to the console when the button is clicked. The onClick attribute of the button element is set to the handleClick function.
Event pooling is a performance optimization technique used by React. When an event occurs, React creates a synthetic event object which is then passed to the event handler function. After the event handler has been invoked, React clears the properties of the synthetic event object and reuses it for other events to reduce the memory overhead.
This means that you cannot access the synthetic event object in an asynchronous way. If you try to access the event properties outside the event handler function, you will get null or undefined.
1 function App() { 2 function handleClick(event) { 3 setTimeout(() => { 4 console.log(event.target); // Will log null 5 }, 1000); 6 } 7 8 return ( 9 <button onClick={handleClick}> 10 Click me 11 </button> 12 ); 13 } 14 15 export default App; 16
In the above example, trying to log event.target after a delay of 1 second will log null because React has already cleared the properties of the synthetic event object.
React implements a synthetic event system which is a cross-browser wrapper around the browser's native event. Synthetic events in React have the same interface as native events, including methods like stopPropagation() and preventDefault(), and their behavior is consistent across different browsers.
Synthetic events provide several benefits:
Here is an example of using a synthetic event in React:
1 function App() { 2 function handleClick(event) { 3 event.preventDefault(); 4 console.log('Button clicked'); 5 } 6 7 return ( 8 <button onClick={handleClick}> 9 Click me 10 </button> 11 ); 12 } 13 14 export default App; 15
In the above example, the handleClick function is an event handler function that prevents the default action of the button click event using the preventDefault method of the synthetic event object and then logs a message to the console.
React functional components are a simpler way to write components that only contain a render method and don’t have their own state. They are also often referred to as "stateless components".
React Hooks are a new addition in React 16.8 that lets you use state and other React features without writing a class. Hooks are functions that let you “hook into” React state and lifecycle features from functional components.
One of the most commonly used hooks is the useState hook, which allows you to add state to your functional components. You can use this hook to store the state of your event handlers.
Here is an example of using the useState hook for event handling in a functional component:
1 import React, { useState } from 'react'; 2 3 function App() { 4 const [count, setCount] = useState(0); 5 6 function handleClick() { 7 setCount(count + 1); 8 } 9 10 return ( 11 <div> 12 <p>You clicked {count} times</p> 13 <button onClick={handleClick}> 14 Click me 15 </button> 16 </div> 17 ); 18 } 19 20 export default App; 21
In the above example, the useState hook is used to create a state variable count and a corresponding setter function setCount. The handleClick function is an event handler function that increments the count state variable when the button is clicked.
The useEffect hook is another commonly used hook in React. It allows you to perform side effects in your functional components. Side effects could be data fetching, subscriptions, or manually changing the DOM.
You can use the useEffect hook to perform side effects related to your events. The useEffect hook takes two arguments: a function where you can put your effect, and an array of values which the effect depends on.
Here is an example of using the useEffect hook for event handling in a functional component:
1 import React, { useState, useEffect } from 'react'; 2 3 function App() { 4 const [count, setCount] = useState(0); 5 6 useEffect(() => { 7 document.title = `You clicked ${count} times`; 8 }, [count]); 9 10 function handleClick() { 11 setCount(count + 1); 12 } 13 14 return ( 15 <div> 16 <p>You clicked {count} times</p> 17 <button onClick={handleClick}> 18 Click me 19 </button> 20 </div> 21 ); 22 } 23 24 export default App; 25
In the above example, the useEffect hook is used to update the document title whenever the count state variable changes. The handleClick function is an event handler function that increments the count state variable when the button is clicked.
Form events are a category of events in React that are specifically associated with forms and form elements. They are crucial for capturing user input and implementing user interactions.
The onChange event in React is triggered when the user changes the input value of a form field. It's often used to update the state of a component when the value of a form field changes.
Here is an example of handling the onChange event in a functional component:
1 import React, { useState } from 'react'; 2 3 function App() { 4 const [name, setName] = useState(''); 5 6 function handleChange(event) { 7 setName(event.target.value); 8 } 9 10 return ( 11 <div> 12 <input type="text" value={name} onChange={handleChange} /> 13 <p>Hello, {name}!</p> 14 </div> 15 ); 16 } 17 18 export default App; 19
In the above example, the handleChange function is an onChange event handler that updates the name state variable with the new input value when the value of the input field changes.
The onSubmit event in React is triggered when a form is submitted. It's often used to prevent the default form submission behavior and perform some action when the form is submitted.
Here is an example of handling the onSubmit event in a functional component:
1 import React, { useState } from 'react'; 2 3 function App() { 4 const [name, setName] = useState(''); 5 6 function handleChange(event) { 7 setName(event.target.value); 8 } 9 10 function handleSubmit(event) { 11 event.preventDefault(); 12 console.log(`Form submitted with input value: ${name}`); 13 } 14 15 return ( 16 <form onSubmit={handleSubmit}> 17 <input type="text" value={name} onChange={handleChange} /> 18 <input type="submit" value="Submit" /> 19 </form> 20 ); 21 } 22 23 export default App; 24
In the above example, the handleSubmit function is an onSubmit event handler that prevents the default form submission behavior and logs a message to the console with the input value when the form is submitted.
Mouse events are a category of events in React that are specifically associated with the mouse actions. They are crucial for implementing user interactions that involve the mouse.
The onClick event in React is triggered when the user clicks on an element. It's often used to perform some action when the user clicks on an element.
Here is an example of handling the onClick event in a functional component:
In the above example, the handleClick function is an onClick event handler that increments the count state variable when the button is clicked.
The onMouseOver event in React is triggered when the mouse pointer moves over an element. It's often used to change the style of an element when the mouse pointer moves over it.
Here is an example of handling the onMouseOver event in a functional component:
1 import React, { useState } from 'react'; 2 3 function App() { 4 const [color, setColor] = useState('blue'); 5 6 function handleMouseOver() { 7 setColor('red'); 8 } 9 10 function handleMouseOut() { 11 setColor('blue'); 12 } 13 14 return ( 15 <div> 16 <p style={{ color: color }} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}> 17 Hover over me 18 </p> 19 </div> 20 ); 21 } 22 23 export default App; 24
In the above example, the handleMouseOver function is an onMouseOver event handler that changes the color of the text to red when the mouse pointer moves over it. The handleMouseOut function is an onMouseOut event handler that changes the color of the text back to blue when the mouse pointer moves out of it.
Keyboard events are a category of events in React that are specifically associated with keyboard actions. They are crucial for implementing user interactions that involve the keyboard.
The onKeyDown event in React is triggered when the user presses a key on the keyboard. It's often used to perform some action when the user presses a specific key.
Here is an example of handling the onKeyDown event in a functional component:
1 import React from 'react'; 2 3 function App() { 4 function handleKeyDown(event) { 5 if (event.key === 'Enter') { 6 console.log('Enter key was pressed'); 7 } 8 } 9 10 return ( 11 <div> 12 <input type="text" onKeyDown={handleKeyDown} /> 13 </div> 14 ); 15 } 16 17 export default App; 18
In the above example, the handleKeyDown function is an onKeyDown event handler that logs a message to the console when the Enter key is pressed.
The onKeyUp event in React is triggered when the user releases a key on the keyboard. It's often used to perform some action when the user releases a specific key.
Here is an example of handling the onKeyUp event in a functional component
1 import React from 'react'; 2 3 function App() { 4 function handleKeyUp(event) { 5 if (event.key === 'Enter') { 6 console.log('Enter key was released'); 7 } 8 } 9 10 return ( 11 <div> 12 <input type="text" onKeyUp={handleKeyUp} /> 13 </div> 14 ); 15 } 16 17 export default App; 18
In the above example, the handleKeyUp function is an onKeyUp event handler that logs a message to the console when the Enter key is released.
Event throttling and debouncing are techniques used to limit the rate at which a function is executed. Throttling ensures that a function is not called more than once in a specified time period, while debouncing ensures that a function is not called until a certain amount of time has passed since the last time it was called. These techniques can be particularly useful for improving performance in event handlers that are attached to events that fire frequently, such as scroll or resize events.
Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. With bubbling, the event is first captured and handled by the innermost element and then propagated to the outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements. Understanding these concepts is crucial for correctly handling events and preventing unwanted side effects in your React applications.
In conclusion, mastering event handling in React is a journey that opens up a world of possibilities for creating interactive and dynamic user interfaces. From understanding the basic syntax of event handlers, the nuances of synthetic events, and event pooling, to the advanced concepts of event throttling and debouncing, each step deepens your knowledge and equips you with the tools to tackle complex UI challenges. Whether you're handling form events, mouse events, or keyboard events, the principles remain the same, and the power of React's event-handling system is at your fingertips.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.