May 29, 2019
-
Clone the repo and
cd
into the project -
Install dependencies:
yarn
- Start the dev server:
yarn start
Hooks are functions which lets you reuse stateful logic (without changing your component hierarchy)
Here's a simple React component:
import React, { 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>
);
}
This helps us avoid creating a wrapper hell of components and solves problems with using patterns such as higher order components and render props.
- React hooks were introduced in v16.8
- Added in the recent React Native release v0.59
- Completely opt-in with no breaking changes
- Classes will still work
Read the motivation behind hooks
- Reduce complexity of components by creating smaller reusable stateful functions.
- Co-locate the stateful logic together
- Think setting up an event listener on mount and removing it before unmount
- Easier to write tests
- Avoids needs for an external state management library
- Instead of separating out component logic based on lifecycles, think about separating stateful logic in terms of the functionality it provides. Think:
- use network status?
- use device orientation?
- use clip board?
- use your imagination...
- Use react without classes
class
is just a syntactical sugarthis
doesn't work the same way in javascript as it works in other languages- react components are closer to functions (as is javascript)
- with the advent of frontend frameworks (such as Svelte) we're looking at the next level of optimizations
- ahead of time compilation
- classes are harder to optimize
- don't minify well
- makes hot reloading flaky
useState
hook to refactorCounterClass
intoCounterWithHooks
- Creating a custom hook
useDocumentTitle
- set the title after updating count
- set a title initially
- set a title initially and let it update as we keep increasing count
Wanna discuss something? Drop me a message @divyanshu013 or slack @divyanshu
👋