React Hooks
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
Post a Comment