13

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>
);
5
  • I think both variants are not equivalent. Using JSX hides the actual React.createElement('MyComponent', {value}, null) part. I'm not saying this won't work, but option A looks odd to me. Commented Mar 21, 2019 at 12:53
  • @lipp yea I realise the difference, my question is if that difference matters Commented Mar 21, 2019 at 12:57
  • 1
    That said, I'd assume that option A invokes useEffect as a nested function of RenderPropComponent and thus should be avoided. Commented Mar 21, 2019 at 12:57
  • It's really an interesting question! I'd bet option A is discouraged :) Commented Mar 21, 2019 at 13:00
  • For instance, RenderPropComponent could call children(value) conditionally. Commented Mar 21, 2019 at 13:02

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Specifically (as of at least [email protected], if not earlier), React will throw an error indicating the order of called hooks has changed, as the hook call stack extends through non-Component functions called within a Component (including render props).
2

This does not break the rules of hooks - https://unsplash.com/blog/calling-react-hooks-conditionally-dynamically-using-render-props/#waitdoesntthisbreaktherulesofhooks

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.