React Hooks basics
Adam Dudley
VP of Strategy & Alliances at Nucleus | Helping Organizations Prevent Breaches by Automating Risk-Based Vulnerability Management at Scale | Interests: Cyber, AI, Venture Capital, Longevity, Startups, Markets & Economics
This article originally appeared here on my blog, Cosmic Source Code.
For more insight into React Hooks, check out this video, on the Facebook Developers YouTube channel, which informed much of the content for this post.
React Hooks allow you to reuse stateful logic across components without having to change your component hierarchy. Additionally, Hooks allow you to split one component into smaller functions based on what pieces are related. Hooks are so named because they are functions that let you hook into React features like state and lifecycle methods without having to use classes in your components.
Check out this code for a simple React todo app (here’s the GitHub repo, which you can fork and clone and run with ‘npm i’ and ‘npm start’):
Here is what’s happening in this component:
Line 1: Import the useState hook from React so we can keep the state in a function component
Line 20: Keep track of the current input value with useState and its two variables, in this case, todo, and setTodo
Line 51 and Lines 27-31: Take the new todo from user input and add it to the end of the current todoList array and then clear the input form
Line 21 and 41-49: Begin with the initialTodoList as the initial state and use setTodoList to update the current todoList with the new contents and display all todos on the page
What do you love or dislike about React Hooks? How are you using them? Please share your insights or examples in the comments.