liveBook · Manning

Local function

As explained in React Quickly, Second Edition

A local function is a function defined within another function and accessible within that enclosing function's lexical scope.

A local function is defined inside a functional component, where it can use component-local information without receiving every value as an argument. section 4.4.3

Choose between these two conversion patterns:

  • Use a pure function outside the component when its inputs can be passed clearly as arguments. section 4.4.3
  • Use a local function when passing many component properties would make the call more complex and less isolated. section 4.4.3
Listing 4.15 Gallery v3 using functions (excerpt)
...
function Image({ index, title }) {
  const getImageSource = () =>                     #1
    `//picsum.photos/id/${index}/150/150/`;        #1
  return (
    <figure style={{ margin: "5px" }}>
      <img src={getImageSource()} alt={title}/>    #2
      <figcaption>
        <h3>Species: {title}</h3>
      </figcaption>
    </figure>
  );
}
...

The Image component defines getImageSource inside itself, allowing the function to read index directly and keeping the JSX call compact. section 4.4.3

How React Quickly, Second Edition covers it

How deep it goes
Compares pure and local functions with concrete calls and JSX, but does not develop deeper implementation internals.
Examples
Uses an Image component whose local getImageSource function builds a Picsum image URL from index.
What you can do after
Apply it via functional components to retain compact calls while accessing component-local values.
How it connects
Connects functional components with class methods, pure functions, props, and JSX.

Also explained in

Compare how 2 books explain local function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.