{"componentChunkName":"component---src-templates-blog-post-js","path":"/explaining-the-benefits-of-using-react-hooks-like-youre-five-with-examples","result":{"data":{"contentfulBlogPost":{"createdAt":"2019-10-21T22:37:53.616Z","updatedAt":"2019-10-22T00:10:06.091Z","id":"0e630a1c-b6a7-5cca-b38e-784a4cd6b5cb","description":"Stop being afraid of Hooks, its time to face your fears and dig into the functional components world. Start to use state in functions.","title":"Explaining the benefits of using React Hooks like you're five - with examples","body":{"id":"ccf4fc99-9e12-5206-ac04-0df7730ab3d3","childMarkdownRemark":{"id":"264d78c9-9d6b-5514-a865-28c9348df27a","html":"<p>Since React.js reached the version 16.8 they introduce the use of Hooks. This was the alternative to enhance the functional components and having the same capabilities of the class components,<a href=\"https://ogaston.com/en/introduction-to-react-difference-between-class-component-and-functional/\">which i write about a time ago</a>.</p>\n<h2>First of all, What are React Hooks?</h2>\n<p>Hooks are a variety of functions, mostly pure, added to the React API that allow us to use all the stateful logic in the funtional components without change its structure.</p>\n<p>The React team explained that they encountered several <em>problems over some years maintaining ten of thousands components</em>. They decide to create a new way of using the state and the lifecycles in components. <a href=\"https://en.reactjs.org/docs/hooks-intro.html#motivation\">You can read here the motivation</a>.</p>\n<p>So, here we show you how you can grasp the concept of Hooks. We'll see the most relevant and how you can migrate a class component easily.</p>\n<h2>useState</h2>\n<p>This is the most common and understandable Hooks, used as a homolgoc of <strong>this.state</strong> with few slightly difference. The useState is a function that receive the initial state of the component and return an array with two values, the first is the current state and the second the \"setState\" function of this state. </p>\n<p>We've created a button component that change the color everytime we click it. we'll see the two ways, with class and after with hooks.</p>\n<h5>Class component</h5>\n<pre><code class=\"language-javascript\">// Class component\n\nclass ButtonRandomColor extends Component {\n\n  \n  constructor(props) {\n    super(props)\n    \n    // initializing the state in the constructor\n    this.state = {\n      currentColor: \"\"\n    }\n    // binding the \"this\" reference to this component. \n    // with hooks we avoid doing this.\n    this.changeColor = this.changeColor.bind(this)\n  }\n\n  // Function to change the color of the state\n  changeColor() {\n    const letters = '0123456789ABCDEF';\n    let color = '#';\n    for (var i = 0; i &#x3C; 6; i++) {\n      color += letters[Math.floor(Math.random() * 16)];\n    }\n    this.setState({\n      currentColor: color\n    }) ;\n  }\n\n  // Render method\n  render() {\n    return (\n      &#x3C;button \n        onClick={this.changeColor}\n        style={{\n          backgroundColor: this.state.currentColor\n        }}>\n        Change My Color\n      &#x3C;/button>\n    )\n  }\n}\n</code></pre>\n<h5>Functional component</h5>\n<pre><code class=\"language-javascript\">function ButtonRandomColor () {\n  const letters = '0123456789ABCDEF';\n  // color is the current state and setColor is the function to change it. \n  // you can assign the name you want, this is possible thanks to destructuring \n  // part of the ES5 capabilities of javascript.\n  const [color, setColor] = React.useState(\"\") \n\n  // We declare the getRandomColor function as an arrow function.\n  const getRandomColor = () => {\n    let color = '#';\n    for (var i = 0; i &#x3C; 6; i++) {\n      color += letters[Math.floor(Math.random() * 16)];\n    }\n    return color\n  }\n\n  // This is the template that will be rendered.\n  return (\n      &#x3C;button \n        onClick={() => setColor(getRandomColor()) }\n        style={{\n          backgroundColor: color\n        }}>\n        Change My Color\n      &#x3C;/button>\n  )\n} \n</code></pre>\n<h5>Differences and beneficts with hooks</h5>\n<ul>\n<li>We dont need to use the entire constructor method.</li>\n<li>The state is not nessesary to be an object. Could be an primitive value (string, number, boolean).</li>\n<li>We save a lot of typing without use \"this\"</li>\n<li>The state aliases make the code more readable.</li>\n<li>Look syntaticaly more simple.</li>\n</ul>\n<h2>useEffect</h2>\n<p>The useEffect hook come to show us how simple the life could be without the life-cycle methods. It allow you to perform side effects in function components. But what does it mean? it means all the operations that run before or after the render process.</p>\n<p>It's commonly used with API request and asynchronous process. Let's take a look with an example.</p>\n<h5>Class component</h5>\n<pre><code class=\"language-javascript\">class LyricViewer extends Component {\n\n  // initializing the state in the constructor\n  constructor(props) {\n    super(props)\n    this.state = {\n      currentLyrics: \"\"\n    }\n    this.getLyric = this.getLyric.bind(this)\n  }\n\n  // Method to retrieve the data and save it in the state.\n  async getLyric() {\n    const { author, song } = this.props\n    const res = await fetch(`https://api.lyrics.ovh/v1/{author}/{song}`)\n    const response = await res.json()\n    this.setState({\n      currentLyrics: response.lyrics\n    })\n  }\n\n  // Retrieves the data when the component is mounted.\n  componentDidMount() {\n    this.getLyric()\n  }\n\n  // It validates if the props has changed to call the componentDidUpdate method. \n  // It help to avoid unnecessary requests\n  componentShouldUpdate(nextProps) {\n    const { author, song } = this.props\n    if (nextProps.author === author &#x26;&#x26; nextProps.song === song) {\n      return false\n    }\n    return true\n  }\n\n  // Retrieve the data again if the props change.\n  componentDidUpdate() {\n    this.getLyric()\n  }\n\n  // Render the lyrics\n  render() {\n    return (\n      &#x3C;div>\n        {this.state.currentLyrics}\n      &#x3C;/div>\n    )\n  }\n}\n</code></pre>\n<h5>Functional component</h5>\n<pre><code class=\"language-javascript\">// Here, we're using destructuring to get\n// just what we want of the props object passed as parameter.\nfunction LyricViewer ({ author, song }) {\n  const [lyrics, setLyrics] = React.useState(\"\")\n\n  const  getLyric = async () => {\n    const res = await fetch(`https://api.lyrics.ovh/v1/{author}/{song}`)\n    const response = await res.json()\n    setLyrics(response.lyrics)\n  }\n\n  // Bellow is the important part of this snippet\n  // This funciton will be called when our component is mounted\n  // and/or some of these variables passed as second parameter in the array \n  // change their value.\n  React.useEffect(() => {\n    getLyric()\n  },[author, song]) \n  // If author or song value change, the useEffect will run again.\n\n  // Template\n    return (\n      &#x3C;div>\n        {lyrics}\n      &#x3C;/div>\n    )\n} \n</code></pre>\n<h5>Differences and beneficts with hooks</h5>\n<ul>\n<li>We replace three methods just with one function.</li>\n<li>This approach simplify the rendering process of the component.</li>\n<li>useEffect evaluate itself when it should update (no componentShouldUpdate needed). </li>\n<li>Almost the 60% of the code has been reduced.</li>\n<li>Practically, the same beneficts of the past hook.</li>\n</ul>\n<h2>Others Hooks</h2>\n<p>Based in prevous hooks we cover here, the React team has implemented for us almost 8 hooks, we won't dig depper here but let's check some of the most relevant:</p>\n<ul>\n<li><strong>useContext:</strong> Receive a React's Conext Object and return the current context value. </li>\n<li><strong>useReducer:</strong> It's very similar to useState, but it use a reducer (like Redux) and the initial state to return the current state and the dispatcher function.</li>\n<li><strong>useCallback:</strong> It's useful when we need to memorize \"high-weight\" operations. Returns the memorized callback. </li>\n<li><strong>useRef:</strong> It returns a mutable object whose <em>current</em> property value is passed as argument. </li>\n</ul>\n<p>Basically, these hooks have more advanced use, and might not be used frecuently. If you want read more about check the <a href=\"https://en.reactjs.org/docs/hooks-intro.html#motivation\">official react documentation</a>.</p>\n<h2>So, Hooks worth it?</h2>\n<p>Totally yes, we kinda prove it above. At the beginnig is a little confusing forget about the \"class\" schema but i guarantee you that using them you can improve your productivity writing them more easyly. </p>\n<p>This is the new approch is taking React, but we are not obligate to migrate all our existing app to hooks so it's good to stat using and prepare the new projects to the innovation of the library.</p>\n<p>So, tell me. Do you already use Hooks? Comment bellow and share!</p>","excerpt":"Since React.js reached the version 16.8 they introduce the use of Hooks. This was the alternative to enhance the functional components and having the same capabilities of the class components,which i write about a time ago. First of all, What are React Hooks? Hooks are a variety…"}},"image":{"id":"e8dec582-860a-5774-b84f-ae1aa5b7cbad","fluid":{"base64":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAALABQDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAAUIB//EACYQAAEDAwMCBwAAAAAAAAAAAAECAwQABhEFMUESEyEiI1FhssH/xAAWAQEBAQAAAAAAAAAAAAAAAAAGBAX/xAAiEQABAwMDBQAAAAAAAAAAAAABAAIDBAYRBUGRFTFhcZL/2gAMAwEAAhEDEQA/AMduC/rSY0NpzTtRbjSF4Cmn0lKmyffw4+M0huG44duSoiXdV7yZIVltfqbY26P08jHNTTq0+S8olby1E75NLokh1DmErUAeAa1I9ZnaxFG2dSxSkiRxBJ74J5xt6VOxrvtZ5rqeRJacJOUpQnH2oqf2JDvbHnNFS9ZqPHCQi3KXZzvpf//Z","aspectRatio":1.881720430107527,"src":"//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=786&q=50","srcSet":"//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=197&h=105&q=50 197w,\n//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=393&h=209&q=50 393w,\n//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=700&h=372&q=50 700w","srcWebp":"//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=786&q=50&fm=webp","srcSetWebp":"//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=197&h=105&q=50&fm=webp 197w,\n//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=393&h=209&q=50&fm=webp 393w,\n//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=700&h=372&q=50&fm=webp 700w","sizes":"(max-width: 786px) 100vw, 786px"}}}},"pageContext":{"slug":"explaining-the-benefits-of-using-react-hooks-like-youre-five-with-examples","intl":{"language":"en","languages":["en","es"],"messages":{"title":"Omar Gaston","navbar.knowme":"About me","navbar.projects":"Projects","navbar.contact":"Contacts","frontpage.readMyBlog":"Read my blog","frontpage.knowme":"Who am I?","blog.subtitle":"Creating stories.","blog.title":"Sharing my ideas","blog.text":"with the community.","subscribe":"Subscribe","changeLanguage":"ES","goBack":"Go back","viewOnGithub":"View on Github","viewProject":"View Project","viewMore":"See more","notFound.title":"NOT FOUND","notFound.text":"You just hit a route that doesn't exist... what sadness! ","notFound.knowAuthor":"well, this guy","notFound.goBlog":"Better go and read something","notFound.whoSay":"...Who say that?","personal.title":"Who I Am?","personal.fullname":"Omar Gaston Chalas","personal.salute":"Hi, I'm","personal.presentation":"A Javascript Full-Stack Developer, Lover of creating products which make people's life easier.","personal.presentationContinue":"I'm always eager to hear about new ideas, create and learn new things.","personal.coverletter":"Well I'm Omar, a Dominican Software Engineer passionate about Javascript, web development and related technologies. As a developer, I've been building highly scalable business apps for more than 3+ years caring deeply about the details in both well-crafted code and user-facing experience. ","personal.coverletterContinue":"Since I remember, I've always been curious and eager to learn new technologies and acquire new skills. Constant learning and a proactivity attitude have allowed me to be comfortable with the rapid changes which are already common in the modern tech industry.","personal.coverletterContinue2":"Despite I care about keeping my technical skills shaped, I also have a Startup mindset and pragmatic attitude, that comes with a willingness to lead projects and desire to understand about the business and where it’s heading","personal.quote":"It's not all about me, As a team player, I love collaborating with others and be involved in Open Source projects. For me, mentoring and helping others is the best way to giving back to those whos have led me in the past.","personal.coverletterFooter":"By the way, These are some of the tools I'm currently using: ","aptitudes.title":"Skills","aptitudes.creativity.title":"Creativity","aptitudes.creativity.text":"The best way to demonstrate authenticity is by being creative.","aptitudes.innovation.title":"Innovation","aptitudes.innovation.text":"Experiment and apply new technologies.","aptitudes.focused.title":"Focus","aptitudes.focused.text":"The correct solutions arise by dividing a problem and focusing on each part.","aptitudes.consistency.title":"Consistency","aptitudes.consistency.text":"The only way to achieve success is to persevere.","aptitudes.simplest.title":"Simplicity","aptitudes.simplest.text":"It's always good when something works, but when it's simple and works, it's wonderful.","aptitudes.community.title":"♥","aptitudes.community.text":"Work as a team with communities and colleagues.","projects.title":"Projects","projects.text":"Some of the projects I've been working on","contact.title":"Contact","contact.text":"Talk to me and work together.","contact.form.email.label":"Email","contact.form.email.placeholder":"Your email","contact.form.message.label":"Message","contact.form.message.placeholder":"Anything about you, your work or your pet :)","contact.form.submit":"Send","contact.form.secondmessage":"Tell me, what's going on?","contact.writeme":"Write me!","lastPost.title":"Latest posts","search.result":"result","search.noresult":"No results for","search.search":"Search"},"routed":false,"originalPath":"/explaining-the-benefits-of-using-react-hooks-like-youre-five-with-examples","redirect":false}}}}