Explained: React Hooks

When using React without hooks, you may find yourself passing props from function components to class components which can cause very unnecessary stress and confusion and may result in you finding long workarounds to solve the problem. React Hooks will help solve some of these problems.

Using Hooks

useState: one of the most common hooks. useState passes back an initial state value and an update method for this state. (update method functions very similarly to a setState in class components)

import { useState } from 'react';

function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

Notice the line where we declared the ‘count’ variable. If we were not to use hooks our code would have looked like this:

import React, { Component } from 'react';

export class ReactWithoutHooks extends Component {
constructor(props) {
super(props;
this.state = {
count: 0
}
}

render() {
const { count} = this.state;
return (
<div className="App">
<header className="App-header">
You clicked the button: { count} times.
<button
onClick={() => this.setState({ count: count+ 1 }) }
>
Click me!
</button>
</header>
</div>
)
}
}

Hooks allows us to define/manipulate the state without making us change alot of code. Not to mention that the code is alot cleaner and shorter.

If multiple states are needed and they are being used in different locations in your form, the useState hook will be extremely useful.

const LoginForm = () => {
const [login, setLogin] = useState({ email: '', password: '' });

return (
const { handleSubmit } = this.props;
<div className="App">
<header className="App-header">
<form onSubmit={handleSubmit}>
<input value={ login.email } onChange={(e) => setLogin(prevState => { ...prevState, email: e.target.value }) } />
<input value={ login.password } onChange={(e) => setLogin(prevState => { ...prevState, password: e.target.value }) } />
<button type="submit">Submit</button>
</form>
</header>
</div>
)
}

Of course, there are other hooks besides useState and you can even create your own custom hooks, but Ifound that the useState hook is very common and a good entry point to learning about React Hooks.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store