First Experience on React Hooks

Hi!

I and my cro-magnon-brain want to share our opinion about react hook that has been around since v16.8. But for now only UseState and UseEffect, so we will have another story to share for another time :).

Disclaimer:
I’m not that familiar with technical terms so I choose words that I can easily related to. Feel free to correct me :)

Based on Reacts documentation’s

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.

UseState

Here’s an example from my tinder-clone practice

To declare a hook you need to follow the format.

const [state,function_to_setState] = useState(initial_state);

Based on that format we will have to define our state and with the code snippet above messages state with objects as the initial value we also need to declare which function that will be responsible to change the states value.

I saw that as a private setState for each state declared because from the example messages has setMessages and input has setInput with their respective default values.

pic. 1

Lets see pic. 1. I typed Happy New Year in input. The “Happy New Year” text will be saved to input state by input form onChange (see snip. 2) using setInput. We can see setInput as

setState({input:"Happy New Year"})
snip. 2
pic. 2

Then when the send button pressed the handleSend function (see snip. 1) will be fired and will set or update the messages state value with the value of input state using setMessages which is basically

setState({messages:[...this.state.messages,{message:this.state.input}])

UseEffect

By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.

UseEffect is similar to componentDidMount and ComponentDidUpdate.

Here’s the example

snip. 3

This snippet code format is

useEffect(()=>{ code_here },[])

from the tutorial I followed (also see snip.3). If the [] is empty this useEffect only runs once after the component is mounted just like componentDidMount and if the [] is filled for example with people state, it will runs every time people state is updated.

subscribe and unsubscribe is part of the firebase flow which will discussed in the future

Pros and Cons

But…

I think it will be quite difficult to use hooks in big-scale project because you will need to keep track of every state and every functions that change the value.

Sharing is one way to learn new things, the other one is to open for criticisms