bhylu.com

Advertisements

React JavaScript Functions

Distinguish a function value, a call and a callback before attaching event handlers.

How it works

Components and handlers are JavaScript functions with different jobs. A component describes the view; a handler responds to a user action. Arrow functions are convenient for a short callback, but they are not required for every definition. Here formatDays is a pure calculation called during rendering. acknowledge is passed to a button so it runs later. Passing the result of acknowledge() would run it immediately instead.

Run the code

Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.

No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.

Example

src/main.jsx

import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

function formatDays(days) {
  return days === 1 ? '1 day' : days + ' days';
}
function App() {
  const [message, setMessage] = useState('Not acknowledged');
  function acknowledge() {
    setMessage('Notice read');
  }
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <p>Loan period: {formatDays(3)}</p>
      <button onClick={acknowledge}>Acknowledge notice</button>
      <output>{message}</output>
    </main>
  );
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

Expected result

The loan period reads three days. Only clicking the button changes the message to “Notice read”.

formatDays has an explicit input and returns text without changing anything outside itself. acknowledge captures a state setter from App. An inline arrow is useful when an argument must be supplied, such as () => acknowledge(), but adding a wrapper without a reason can obscure the distinction. Recreating a small handler is normally fine; optimize after measuring rather than treating every function as a performance bug.

For API contracts and version differences, use React’s official documentation.

Advertisements