I learned React by passing down props and state to components. There are a lot of things you could do with React in this form. However, things can get repetitive and harder to read as the list of props and state grows. Even more if you are passing all the way down to the very bottom layer of components.
This is where hooks can come in handy. It makes things less repetitive and easier to pass down and pull information between components.
Let's take a look at a simple React component without hooks.
import React, { Component } from 'react';
import ExampleButton from '..components/ExampleButton'
export default function App() {
state = {
text: "Hello World",
toggleOn: true
}
return (
<div>
<ExampleButton text={this.state.text}
toggleOn={this.state.toggleOn}/>
</div>
);
}
In this component, we see that we declared some state attributes and we are passing it down to the ExampleButton component.
import React, { Component } from 'react';
export default function ExampleButton(props) {
return (
<div>
<Button onClick={!props.toggleOn}>{props.text}</Button>
</div>
);
}
In this component, we grabbed the state attributes by using props. However, what if we had more components to use the text "Hello World"? Or more buttons to have a toggle feature? Each time, we have to pass down the state properties and call them using props.
With hooks, you will be able to declare state and just call on specific state properties without having to pass down the props. This is done through the use of useState. It works in a similar fashion as setState. With that, you will also be able to change state into something else.
import React, { useState } from 'react';
import ExampleButton from '..components/ExampleButton'
export default function App() {
state = {
text: "Hello World",
toggleOn: true
}
return (
<div>
<ExampleButton />
</div>
);
}
See the difference? No props are getting passed down to the ExampleButton component. So how will we call these state properties now?
import React, { useState } from 'react';
export default function ExampleButton() {
const [toggleOn, setToggleOn] = useState(!toggleOn)
const [text, setText] = useState('Hello!');
return (
<div>
<Button onClick={toggleOn}>{text}</Button>
</div>
);
}
Here we are using useState to call on any properties of state. This looks much cleaner and easier to read. Also we don't have to worry about properties getting passed down correctly through many different components. We can call directly on any state property by using useState. We can also reset state as demonstrated in the last code block.
Top comments (0)