DEV Community

loading...

😜 My Looks on βš“ Hooks

Afroze Kabeer Khan. M
Full stack Developer. Node Js, JavaScript & React
・3 min read

An article on what i love the most after a long time.
You don't need Class to maintain state hereafter

Functional Stateful Component 🎑

Is that even a word ?

So here we had a traditional way of creating stateful component like Class App extends blah blah blah...

But that's not it here we have functional stateful component like the one below.

import React, { useState } from 'react'; //Importing modules

function App() {

  const [date, updateDate] = React.useState(Date());

  return (
    <div className="App">
      <h1>{date}</h1>
      <button onClick={() => {
        updateDate(Date())
      }}> Update </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Cool uh... 😁

useEffect

That's not it... We have even more cool stuff in the closet. Now that we know how to maintain state in a functional component. So how de we react if there are some effects in the component... πŸ€” Really just useEffect 😜.

Let's handle effective changes.

import React, { useState, useEffect } from 'react'; //Importing modules

function App() {

  let count_p = React.createRef();

  const [date, updateDate] = React.useState(Date());

  React.useEffect(() => {
    count_p.current.textContent = Number(count_p.current.textContent)+1;
  });

  return (
    <div className="App">
      <h1>{date}</h1>
      <button
        onClick={() => {
          updateDate(Date());
        }}
      >
        {" "}
        Update{" "}
      </button>
      <p>You've updated dated <span ref={count_p} ></span> time(s)</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

So everytime you update state the method useEffect is called. There we go.
We're using Ref's here is there a better way? πŸ™„

useRef

There's an another hook we can use from the above example. useRef. Let's use that.

import React, { useState, useEffect, useRef } from 'react'; //Importing modules

function App() {

  let count_p = useRef(null);

  const [date, updateDate] = React.useState(Date());

  useEffect(() => {
    count_p.current.textContent = Number(count_p.current.textContent)+1;
  });

  return (
    <div className="App">
      <h1>{date}</h1>
      <button
        onClick={() => {
          updateDate(Date());
        }}
      >
        Update
      </button>
      <p>You've updated dated <span ref={count_p} ></span> time(s)</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

useContext

So the context which was released has become legacy context. Now there's a new way of writing it.
So let's say i have a context called Ration Context. In this i list i add new ration every year. Once i do that i wanted that to be listed in all ration shops. So we use something called Context. Let's see how it works.

// RationContext.js
import React,{ Component, createContext } from 'react';

// Create a context which gives Provider and Consumer
const RationContext = React.createContext({
    //Add initial values
    ration: [],
    addRation: () => null
});

//export the consumer
export RationConsumer = RationContext.Consumer;

//export the provider with state and other methods
export class RationProvider extends Component {

    constructor(props){
        super(props);
        this.addRation = this.addRation.bind(this);
        this.state = { ration: [] }
    }

    addRation = (ration) => {
        let { ration } = this.state;
        ration.push(ration);
        this.setState({ ration });
    }

    render(){
        let { ration } = this.state;
        let { children } = this.props;

        return(
            <RationContext.Provider value={{ ration, addRation }} >
                {children}
            </RationContext.Provider>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

So we have to list somewhere the rations which is provided. Lets see how to do this using hooks.
For this we need to change a line in RationContext.js

    const RationContext to export const RationContext
Enter fullscreen mode Exit fullscreen mode

Now let's list Rations in RationList.js

    import React,{ useContext } from 'react';
    import { RationContext } from './RationContext';

    export const RationList = () => {
        let { rations } = useContext(RationContext);

        return(
            <div>
                <ul>
                    {rations.map(ration => <li>{ration}</li>)}
                </ul>
            </div>
        )
    }
Enter fullscreen mode Exit fullscreen mode

Cool. Now let's add ration from AddRation.js

    import React,{ useContext, useState } from 'react';
    import { RationContext } from './RationContext';

    export const AddRation = () => {
        let { addRation } = useContext(RationContext);

        updateRation = (e) => { e.keyCode === 13 ? addRation(e.value) : '' }

        return(
            <div>
                <input type="text" placeholder="Ration name" onKeyDown={updateRation}/>
            </div>
        )
    }
Enter fullscreen mode Exit fullscreen mode

Context is no magic it sits on top of the DOM Tree πŸ•΅πŸΌβ€β™‚οΈ and Has its People( Consumer ) down the tree working for it . Here we consider App.js is the entry point of App. Now let's have App.js.

// App.js
import React from 'react';
import { RationProvider } from './RationContext';
import { RationList } from './RationList';
import { AddRation } from './AddRation';

const App = (props) => {
    return(
        <RationProvider>
            <RationList />
            <AddRation />
        </RationProvider>
    )
}
Enter fullscreen mode Exit fullscreen mode

Now i think you must have a good overview of React Hooks. But still there's a lot more to cover for hooks. Expect a part two soon πŸ€—.
Until then Adios... Happy Coding!

Discussion (1)

Collapse
itr13 profile image
Mikael Klages

stuck_out_tongue_winking_eye my looks on anchor hooks