My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Using useState and useEffect

This is an extremely basic explanation of these hooks

Aurobindo Gupta's photo
Aurobindo Gupta
·May 24, 2021·

2 min read

Hooks were added to react 16.8, they let us use State and other React features without using Class components. They have been extremely beneficial for developers, it has improved code reusability, code composition has improved, improved flexibility in moving in the component tree

There are two main rules of using Hooks in React:

  • Make sure to not use Hooks inside loops, conditions, or nested functions.
  • Only use Hooks from inside React Functions.

USESTATE

This hook allows the coder to update, handle, manipulate a state inside the functional components. e.g.(you have to import useState before using it)

function App() {
  const [counter, setCounter] = useState(0);
  const handleClick = () => setCounter(counter+ 1)

  return 
      <div> 
          {counter} 
        <div> 
        <button onClick={handleClick}>Add</button>
      </div>
   </div>
}

the hook receives an initial state as an argument and then returns the updated state value. the first variable is the actual state and the other is a function that is meant for updating the state by providing a new state. In the code snippet above when we click on add button it calls the handleClick function as specified. In the function, we call the setCounter function and pass the value counter+1, which means that the initial value of the state + 1, so the initial value is 0, the new value is set to the state counter. When we call the counter in the div, it gives us the new value 1.

USEEFFECT

This hook gives us the ability to add a side effect to a functional component. For those who have worked with Class components, this serves the same purpose as componentDidMount and componentDidUpdate. When we call the useEffect hook we are asking react to run our "effect". this is declared inside the component so that we have access to its props and state. React runs the effect after every render. Use your side-effect logic in the callback function, then use the dependencies to control when we want the side-effect to run. if the dependency argument is an empty array the side effect only runs once. if it has props or state values, it runs only when the dependency value changes.

useEffect((callback)=>{

},[dependencies])
function eg({ prop }) {
  const [state, setState] = useState();

  useEffect(() => {
    // Side-effect uses `prop` and `state`
  }, [prop, state]);

  return <div>....</div>;
}

In the above code, the useEffect invoked the callback after the changes have been committed to the DOM and IF any value in the dependencies array[prop, state] has changer