0

I want to avoid creating a named component when rendering a child component of a parent. That is, I have the working code below where the dataValueFromContext is returned from InsideComponent and rendered correctly from MyList component (MyContext is available higher in the component tree).

const InsideComponent = () => {
  const { dataValueFromContext } = useContext(MyContext);
  return (
    <span>
      value: {dataValueFromContext}
    </span>
  );
};

export default function MyList() {
  return (
    <div>
      <InsideComponent />
    </div>
  );
}

The problem is that when I want to remove InsideComponent as a named component and nest it anonymously. Something like what I have below, the code does not even compile. I'm basically trying to avoid creating a named function as well as needing a defined function at the top. For me, this makes readability easier.


export default function MyList() {
  return (
    <div>
      {
        () => {
          const { dataValueFromContext } = useContext(MyContext);
          return (
            <span>
              value: {dataValueFromContext}
            </span>
          )
         }
    </div>
  );
}
1

1 Answer 1

1

Two problems:

  1. Your anonymous function component is not being called which means it will never return anything to be rendered.
  2. if you do call it, Eslint will warn you that you can only use a hook inside a functional component's body.

Having that said, you can call the function as follows:

export default function MyList() {
  return (
    <div>
      {
        (() => {
          const { dataValueFromContext } = useContext(MyContext);
          return (
            <span>
              value: {dataValueFromContext}
            </span>
          ))()
         }
    </div>
  );
}

A much better approach is to simply move the useContext outside of return and get rid of the anonymous function all together:

export default function MyList() {
  const { dataValueFromContext } = useContext(MyContext);

  return (
    <div>
       <span>
         value: {dataValueFromContext}
       </span>           
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.