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>
);
React Hooks and render props can co-exist because they solve the same problem of moving state away from your components.
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.)
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.
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]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With