What is this React Hooks thing?
Before we get into the details of Hooks let's just quickly look at the two ways to write components in React.
We’ve got functional components that’s simply JavaScript functions where you can pass in props and return a React element usually used when you don’t need to use state inside the component keeping it dumb or stateless.
const User = props => (
<div>
<h1>Hello, {props.name}</h1>
</div>
);
Then we have class components where you write your components using the ES6 class syntax where you will be able to add state, making the component smarter or stateful as they tend to contain some logic.
class User extends Component {
constructor(props){
super(props);
this.state = {
myState: true;
}
}
render() {
return (
<div>
<h1>Hello {this.props.name}</h1>
</div>
);
}
}
So, of these two approaches I have come to prefer the simplicity of functional components but if there was only a way to use state in there...
This is where the React Hooks thing come into play. Now you can tap into state and other React goodies right from your functional component without the need to resort to writing a class.
Some ground rules for hooks
Let’s review some ground rules we must always follow when working with hooks.
- Never call Hooks from inside a loop, condition or nested function
- Hooks should sit at the top-level of your component
- Only call Hooks from React functional components
- Never call a Hook from a regular function
- Hooks can call other Hooks
A ESLint plugin called eslint-plugin-react-hooks
is available that can help you in enforcing these rules.
npm install eslint-plugin-react-hooks --save-dev
You can start to use hooks if your React version is 16.8.0 or above or if you’re on 0.59 React Native or above.
Now that you know that we can hook into stuff from our functional component let's dive deeper and see how we can hookup. Checkout the other parts:
What is this React Hooks thing?
State & Effects Hooks
Context Hooks
Reducer Hooks
Custom Hooks
Best Practices