ed'
ed'

Reputation: 1895

Using react hooks inside render prop function

Taken from Rules of Hooks:

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function

Given this recommendation by the react team, would using a hook at the top of a render props function be inadvisable? Assuming it depends on the value returned by the function.

const MyComponent = () => (
    <RenderPropComponent>
        {value => {
            React.useEffect(() => {
                // Magic
            }, [value]);

            return <p>Hello</p>;
        }}
    </RenderPropComponent>
);

I don't feel like it breaks their requirement

By following this rule, you ensure that Hooks are called in the same order each time a component renders

But should I be doing the following instead?

const MyComponent = ({ value }) => {
    React.useEffect(() => {
        // Magic
    }, [value]);

    return <p>Hello</p>;
};

const MyContainer = () => (
  <RenderPropComponent>
      {value => <MyComponent value={value} />}
  </RenderPropComponent>
);

Upvotes: 13

Views: 5770

Answers (2)

UjinT34
UjinT34

Reputation: 4977

Hooks keep track of current rendering element. And render prop function is not an element. So you will hook into calling element and not into your prop function. This render prop function will be treated as a custom hook. You will get unexpected behavior if RenderPropComponent calls render prop function conditionally.

Upvotes: 3

Related Questions