Explain Codes LogoExplain Codes Logo

React js onClick can't pass value to method

javascript
onclick
performance
event-handling
Nikita BarsukovbyNikita Barsukov·Aug 8, 2024
TLDR
<button onClick={() => handleEvent(value)}>Click me</button>

In this quick solution, we use an arrow function to neatly pass value to handleEvent. What's the magic here? The this context sticks around as we've ordered.

Enhancing onClick Efficiency

When crafting onClick events, performance, well, matters. So, get rid of creating a new function at each render stroke. Instead, cling onto a stable reference: define the handler outside the render scope or use the useCallback hook in functional form.

// A performance-friendly fellow const handleClick = useCallback(() => handleEvent(value), [value]);

Enlisting Sub-components

No one likes a mess. Wrap your behaviour into a sub-component, accepting props and handling events. Plus point? You get a less congested parent component, while limiting updates to only those components that need it.

Abandoning Re-renders with Memoization

Complex components need special care. Use memoization to cache functions via React.memo or a trusty custom hook. This trick bypasses pointless re-renders when values encore.

Event Handler Hacks and Optimizations

Constructing Bound Handlers

Are you still using ES5 with class components?’ Bind your event handlers in the constructor to ensure 'this' refers to the component instance, and not the phantom of the opera!

constructor(props) { super(props); // Bind it like Beckham! this.handleEvent = this.handleEvent.bind(this); }

Parading Currying in Event Handlers

Do you want to remember a secret recipe of parameters? You'll need currying. It’s not that type of curry, it’s a way of creating a higher-order function. The curry awaits patiently to get called with the event object.

const handleEvent = value => event => { // Sorry, this doesn't come with naan bread 😝 };

Dancing with Data Attributes and Delegation

Passing additional info to event handlers can get pesky. data-* attributes come to the rescue, no inline functions needed!

<button data-value={value} onClick={handleEvent}>Click me</button>

In your handleEvent, bust a little dance move and access value via event.currentTarget.dataset.value.

Keying Your List Items

Hit a perfect harmony with your list rendering: treat each item to a unique key prop. Keys help React spot changes, new performers, or retirees, improving render performance.

Code Architecture and Organisation

Scatter your UI code and event handling logic and you'll have a jigsaw. Define handlers near to the components they operate for maintainability and readability.

Handling Complex Scenarios

Complex components such as tables require single methods to handle onClick for various headers or items. Pass them callbacks as props and follow a hierarchical pattern that mirrors the UI.

Making Roles Clear in Forms

When juggling forms, handleChange comes in super handy for processing various inputs. Keep your handlers on a leash by using a centralized state object or state management.

Patterns for Reusability and Performance

Tackling Repetitive Structures

Give each of your components the best chance to shine. Extract common parts into standalone components for better performance and reusability.

ESLint for Style and Perfection

Use ESLint-plugin-react as the stylist to stick to the best practices while handling events.

Methods in Rendering

Avoid creating multiple function instances during mapping or component rendering. Stick to method references or event handler currying to keep functions steady during re-renders.