Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
);
like image 329
ed' Avatar asked Mar 21 '19 12:03

ed'


People also ask

Can I use hooks in render props?

React Hooks and render props can co-exist because they solve the same problem of moving state away from your components.

Can you use React hooks in functions?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. (We don't recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you'd like.)

Do React hooks work inside classes?

You can't use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component.

Can I use useEffect on props?

Just like the state, we can also use props as a dependency to run the side effect. In this case, the side effect will run every time there is a change to the props passed as a dependency. useEffect(() => { // Side Effect }, [props]);


1 Answers

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.

like image 127
UjinT34 Avatar answered Sep 30 '22 23:09

UjinT34