Tillitsdone
down Scroll to discover

React Hooks: useState and useEffect Guide

Learn the fundamentals of React Hooks with a focus on useState and useEffect.

Discover how to manage state and side effects in functional components with practical examples and best practices.
thumbnail

Introduction to React Hooks: useState and useEffect

Abstract digital art visualization of two interconnected neon rings floating in space representing useState and useEffect hooks with flowing energy streams in bright cyan and magenta colors surrounded by particle effects in a dark void high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Hey there! Today, I’m super excited to dive into one of the game-changing features of React - Hooks! If you’ve been working with React components, you’re about to discover how Hooks can make your code cleaner and more powerful. Let’s focus on the two most commonly used hooks: useState and useEffect.

What are React Hooks?

Think of Hooks as special functions that let you “hook into” React’s features. Before Hooks came along, you needed to write class components to use state and lifecycle methods. Now, we can use these features in functional components - pretty cool, right?

Abstract 3D render of a pulsating digital brain made of glowing lime and electric blue neural networks with energy pathways representing data flow and state management floating in a minimalist space environment high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Understanding useState

The useState hook is like your component’s memory. It helps you keep track of data that can change over time. Let’s look at a simple example:

import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

Here’s what’s happening:

  • useState returns an array with two items: the current state value and a function to update it
  • The initial state (0 in our example) is what we pass to useState()
  • When we call setCount, React knows it needs to re-render our component

Exploring useEffect

3D rendered cosmic scene showing a perpetual motion machine with floating geometric shapes in rose gold and neon purple orchestrating an infinite loop of cause and effect set against a starry background high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

useEffect is your way to handle side effects in your components. Think of it as your component’s connection to the outside world. It’s perfect for:

  • Fetching data
  • Setting up subscriptions
  • Manually changing the DOM

Here’s a practical example:

import { useState, useEffect } from 'react';
function WindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
// Cleanup function
return () => {
window.removeEventListener('resize', handleResize);
};
}, []); // Empty dependency array
return <p>Window width: {width}</p>;
}

The key things to remember about useEffect:

  • It runs after every render by default
  • The dependency array (second argument) controls when it runs
  • The cleanup function (returned function) runs before the component unmounts

Best Practices and Tips

  1. Always name your custom hooks starting with “use”
  2. Keep your hooks at the top level of your component
  3. Don’t call hooks inside loops or conditions
  4. Use multiple useEffects for different concerns
  5. Don’t forget to clean up side effects when necessary

A futuristic space station interior with multiple interconnected chambers glowing with neon blue and lime green light representing React's component hierarchy and state management featuring holographic displays and energy fields high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

These hooks are just the beginning of what’s possible with React. Once you get comfortable with useState and useEffect, you’ll find yourself writing more maintainable and efficient React applications. Happy coding! 🚀

Remember: Practice makes perfect, so don’t worry if it takes some time to get used to thinking in hooks. Keep experimenting and building things!

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.