Codementor Events

STEP BY STEP EXAMPLES OF REACT HOOKS

Published Nov 19, 2018Last updated Nov 28, 2018
STEP BY STEP EXAMPLES OF REACT HOOKS

Hooks allows us to add state to a functional component. 😮

Using Hooks Requires react "next"

So, use "next" in your package.json to get the latest version of it.

// package.json
"react": "next",
"react-dom": "next"

OR

npm install react@next react-dom@next

Screen Shot 2018-10-30 at 1.13.14 PM.png

We are covering 4 hooks of react

  1. useState
  2. useEffect
  3. useContext
  4. useRef

useState

An example for increment/decrement value with reset button.

Example code:

import React, {
  useState
} from 'react';

function Demo1() {
  const [count, setCount] = useState(0);
  return (
    <div>
      Count: {count}
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
    </div>
  );
}
export default Demo1;

Description:

  • Start by importing useState from react. Make a functional component and use useState() therein. useState() is used to declare a state variable and can be initialized with any type of value. As seen above, we use destructuring on the return value of useState.
  const [count, setCount] = useState(0);
  • The first value, count in this case, is the current state (like this.state) and
    The second value setCount is a function used to update the state (first) value.
    The 0 in useState(0) function is Initial Value of that particular state.

useEffect

Lets see an example for changing webpage title in realtime.

Example code:

function Demo2() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Description:

  • Just like we did in previous example by importing useState. Here same we will import useEffect from react. Make a functional component and use useEffect() therein. useEffect() is used to write function statements and as seen above we are changing title of webpage.

  • useEffect is similar to componentDidMount and componentDidUpdate of React Lifecycles.

  • Hence, whenever you click on the button, the title text will change with (number of) counts. Like.. You clicked (n) times.

useContext

Lets see an example for useContext.

const TestContext = React.createContext();

function Display() {
  const value = useContext(TestContext);
  return <div>{value}, I am learning react hooks.</div>;
}

function App() {
  return (
    <TestContext.Provider value={"Kaleem"}>
      <Display />
    </TestContext.Provider>
  );
}

Description:

  • In the code above, the context TestContext is created using React.createContext(). I have use the TestContext.Provider in our App component and set the value there to "Kaleem". This means any context-reading object in the tree can now read that value.

  • To read this value in the Display() function we call useContext, passing the TestContext an argument.

  • We then pass in the context object we got from React.createContext, and it automatically outputs the value. When the value of the provider updates, this Hook will trigger a rerender with the latest context value.

useRef

Refs provide a way to access the React elements created in the render() method.

Lets see an example for useRef.
  • The useRef() function returns a ref object.
function App() {
  let [name, setName] = useState("Nate");

  let nameRef = useRef();

  const submitButton = () => {
    setName(nameRef.current.value);
  };

  return (
    <div className="App">
      <p>{name}</p>

      <div>
        <input ref={nameRef} type="text" />
        <button type="button" onClick={submitButton}>
          Submit
        </button>
      </div>
    </div>
  );
}

Description:

  • In the example above, we're using the useRef() hook in conjunction with the useState() to render the value of the input tag into a p tag.

  • The ref is instantiated into the nameRef variable. The nameRef variable can then be used in the input field by being set as the ref. Essentially, this means the content of the input field will now be accessible through ref.

  • The submit button in the code has an onClick event handler called submitButton. The submitButton function calls setName (created via useState).

  • As we've done with useState hooks before, setName will be used to set the state name. To extract the name from the input tag, we read the value nameRef.current.value.

  • Another thing to note concerning useRef is the fact that it can be used for more than the ref attribute.

Have a read to the Official Docs too: here

Thanks for the read.

please let me know if you have any doubt/query in comment section below.

Please Note: This github repository/demo doesn't contain code related to this post.

Demo: https://react-hooks-demo.firebaseapp.com
Code: Github Code
Github profile:

Kaleem Elahi

Discover and read more posts from Kaleem Elahi
get started
post commentsBe the first to share your opinion
Show more replies