What are React Hooks?
hooks are functions that:
- may call other Hooks.
- have a name with the use prefix.
- If your function contains hooks, you should prefix it with use.
- If your function does not contain hooks, you should prefix it with get. This way you are sure that it does not contain a React state and should not follow the rule of hooks.
See State example
Hooks let you:
- reuse logic between components without changing your component hierarchy.
- split one component into smaller functions based on what pieces are related.
- use React without classes.
Primitive for sharing stateful logic.
React doesn’t offer a way to “attach” reusable behavior to a component (for example, connecting it to a store). If you’ve worked with React for a while, you may be familiar with patterns like render props and higher-order components that try to solve this. But these patterns require you to restructure your components
With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components.
Each lifecycle method often contains a mix of unrelated logic such as:
- sets up event listeners, with cleanup
Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods.
Invalid hook call
In the log, you may see this error:
Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
The invalid-hook-call gives more information but forgot to mean what it means to be inside the body of a function component.
If you have tried all solution and that it's not working, wrap it in a react element like that:
let App = React.createElement(yourfunction, props, ...children);
Documentation / Reference
- https://reactjs.org/docs/hooks-overview.html - Getting started