React Hooks

     I've been continuing along in my studies of React, and I'm learning now about the power of hooks, a method of passing data and functions to components. I have a coworker who has been absolutely thrilled by their addition since he began working on a project new enough to include them, so I figured they must be pretty valuable. Boy was he right, hooks are a simple (although add-looking at first glance) way to pass data down to child components. I've included a snippet sample code I wrote while following this video by Samer Buna.
 
    If you aren't familiar with React (I'm only just getting started), we can sort of read this from the bottom-up. The ReactDom.render() is what will render our HTML (we don't write HTML in React, we write JavaScript to render HTML). It first calls component App(), which we see on line 16. On line 17 we see the hooks, which I'll talk about in a moment. This component is our main component that will render other components, it's sort of like the granddaddy of our program, its children being the Button() component and the Display() component. App() will render a button that says 'Add One', when clicked that button will add one to the value found in Display().

    The trickiest thing about hooks for me is just how they look. They're kind of weird, and my brain can't really make any sense of their syntax right away. But it can be broken down with a little effort! Line 17 is our hook. We can break that line down like this:

const [stateObject, updateFunction] = useState();

or even more simply,

  const [getter, setter] = useState();

    It feels similar to generating properties in C#:

public int object { get; set; }

     On line 18 of our code snippet we initialize the 'setter' (setCounter). We can then magically pass that function like a variable on to our Button() component, and pass our 'getter' (counter) down to our Display() component. They then communicate upwards (like a hook yanking a fish up from the depths), which allows our button to set the new value for our counter (Try pasting this code snippet into this playground!).

    There are a couple other important things to note: once data is passed to our components via props, it must be accessed like an object, which is why we access our message by calling props.message. It's also important to note that hooks can only send data upwards; so we couldn't put line 16 in our Display() component, because it cannot pass data to the side (i.e. hooks create a parent-child relationship, not a sibling to sibling relationship).

 


Comments

Popular posts from this blog

Reviewing WPF and MVVM

Using WebRTC to build a videophone in React and TypeScript

Learning Flutter