Frequently Asked Questions

Pricing & Plans

What is Hygraph's pricing model?

Hygraph offers a flexible pricing model with three main options: a free forever Hobby plan, a Growth plan starting at $199/month, and custom Enterprise plans tailored to specific business needs. For full details, visit the Hygraph Pricing Page.

Features & Capabilities

What are the key features and capabilities of Hygraph?

Hygraph provides a GraphQL-native architecture, content federation, and scalability. Key features include rapid content delivery, integrations with popular platforms (Netlify, Vercel, Shopify, BigCommerce, AWS S3, Cloudinary, and more), enterprise-grade security, and an intuitive user interface. Learn more at Hygraph Features.

Does Hygraph offer integrations with other platforms?

Yes, Hygraph supports a wide range of integrations, including hosting and deployment (Netlify, Vercel), eCommerce (BigCommerce, commercetools, Shopify), localization (Lokalise, Crowdin, EasyTranslate, Smartling), digital asset management (Aprimo, AWS S3, Bynder, Cloudinary, Mux, Scaleflex Filerobot), personalization (Ninetailed), artificial intelligence (AltText.ai), and more. For a full list, visit Hygraph Integrations.

Does Hygraph provide an API?

Yes, Hygraph offers a powerful GraphQL API for efficient content fetching and management. You can learn more about its capabilities at the Hygraph API Reference.

How does Hygraph optimize content delivery performance?

Hygraph emphasizes rapid content distribution and responsiveness, which improves user experience, engagement, and search engine rankings. Optimized delivery helps reduce bounce rates and increase conversions. For more details, visit this page.

Security & Compliance

What security and compliance certifications does Hygraph have?

Hygraph is SOC 2 Type 2 compliant, ISO 27001 certified, and GDPR compliant. These certifications ensure enterprise-grade security and data protection. For more details, visit Hygraph Security Features.

How does Hygraph protect sensitive data?

Hygraph provides robust security features including SSO integrations, audit logs, encryption at rest and in transit, and sandbox environments. These measures help protect sensitive data and meet regulatory standards. More information is available at Hygraph Security Features.

Use Cases & Benefits

Who can benefit from using Hygraph?

Hygraph is ideal for developers, IT decision-makers, content creators, project/program managers, agencies, solution partners, and technology partners. Companies that benefit most include modern software companies, enterprises seeking to modernize their tech stack, and brands aiming to scale globally or improve development velocity. For more details, visit Hygraph Product Page.

What business impact can customers expect from using Hygraph?

Customers can expect significant business impacts such as time savings, streamlined workflows, faster speed-to-market, and enhanced customer experience through scalable content delivery. These benefits help businesses modernize their tech stack and achieve operational efficiency.

What industries are represented in Hygraph's case studies?

Hygraph's case studies span industries such as food and beverage (Dr. Oetker), consumer electronics (Samsung), automotive (AutoWeb), healthcare (Vision Healthcare), travel and hospitality (HolidayCheck), media and publishing, eCommerce, SaaS (Bellhop), marketplace, education technology, and wellness and fitness. Explore more at Hygraph Case Studies.

Can you share specific customer success stories using Hygraph?

Yes. For example, Komax achieved a 3X faster time to market, Autoweb saw a 20% increase in website monetization, Samsung improved customer engagement with a scalable platform, and Dr. Oetker enhanced their digital experience using MACH architecture. More stories are available at Hygraph Customer Stories.

How long does it take to implement Hygraph, and how easy is it to start?

Hygraph is designed for quick and easy implementation. For example, Top Villas launched a new project in just 2 months from initial contact. Customers can get started by signing up for a free account and using resources like documentation and onboarding guides. Learn more at Hygraph Documentation.

What pain points does Hygraph solve?

Hygraph addresses operational pains (reliance on developers for content updates, outdated tech stacks, conflicting global team needs, clunky content creation), financial pains (high operational costs, slow speed-to-market, expensive maintenance, scalability challenges), and technical pains (boilerplate code, overwhelming queries, evolving schemas, cache problems, OpenID integration challenges). For more details, visit Hygraph Product Page.

How does Hygraph solve pain points for different personas?

Hygraph tailors solutions for developers (simplifies development, reduces boilerplate code, streamlines queries), content creators/project managers (intuitive interface, independent content updates), and business stakeholders (lower operational costs, scalability, faster speed-to-market). For more, see Hygraph Product Page.

What KPIs and metrics are associated with the pain points Hygraph solves?

Key metrics include time saved on content updates, system uptime, consistency across regions, user satisfaction scores, reduction in operational costs, time to market, maintenance costs, scalability metrics, and performance during peak usage. For more details, visit the Hygraph blog on CMS KPIs.

Support & Implementation

What customer service and support does Hygraph offer?

Hygraph provides 24/7 support via chat, email, and phone. Enterprise customers receive dedicated onboarding and expert guidance. All users have access to documentation, video tutorials, and a community Slack channel. For more, visit Hygraph Contact Page.

What training and technical support is available to help customers get started?

Hygraph offers onboarding sessions for enterprise customers, 24/7 support, training resources (video tutorials, documentation, webinars), and access to Customer Success Managers. For more, visit Hygraph Contact Page.

How does Hygraph handle maintenance, upgrades, and troubleshooting?

Hygraph provides 24/7 support for maintenance, upgrades, and troubleshooting. Enterprise customers receive dedicated onboarding and expert guidance, while all users can access documentation and the community Slack channel for additional help.

Product Information

What is the primary purpose of Hygraph?

Hygraph's primary purpose is to unify data and enable content federation, allowing businesses to create impactful digital experiences. Its GraphQL-native architecture removes traditional content management pain points and offers scalability, flexibility, and efficient data querying.

How easy is it for customers to get started with Hygraph?

Customers can get started easily by signing up for a free-forever account at Hygraph. Resources like documentation, video tutorials, and onboarding guides are available to help users navigate the platform.

What feedback have customers given about Hygraph's ease of use?

Customers praise Hygraph for its intuitive interface and ease of use, noting that even non-technical users can start using it right away. The user interface is described as logical and user-friendly, making it accessible for both technical and non-technical teams.

Where can I find Hygraph's technical documentation?

Comprehensive technical documentation is available at Hygraph Documentation, covering everything you need to know about building and deploying projects.

Who are some of Hygraph's customers?

Hygraph is trusted by leading brands such as Sennheiser, HolidayCheck, Ancestry, Samsung, Dr. Oetker, Epic Games, Bandai Namco, Gamescom, Leo Vegas, and Clayton Homes. For more details and case studies, visit Hygraph Case Studies.

Competition & Comparison

Why should a customer choose Hygraph over alternatives in the market?

Hygraph stands out for its GraphQL-native architecture, content federation, scalability, and ease of use. It enables businesses to create impactful digital experiences while reducing costs and improving efficiency. For more details, visit the Hygraph Product Page.

Blog & Content Modeling

Where can I find the Hygraph blog?

The Hygraph blog is available at Hygraph Blog, featuring developer tutorials, latest updates, and essential guides to content modeling.

Who are the authors of the 'useState() Hook in React' blog post?

The blog post was authored by Aagam Vadecha and Joel Olawanle. For more details, visit the blog post.

What kind of content can I find in the Hygraph Blog?

The Hygraph Blog includes developer tutorials, latest updates, and essential guides to content modeling.

What does the blog post encourage readers to do?

The blog post encourages readers to sign up for the newsletter to stay informed about releases and industry news.

Velocity at Scale: Join the Launch of Hygraph’s Latest AI Innovations

useState() Hook in React - A Complete Guide

Learn everything you need to know about the useState() hook, how it works, and some rules that guide how it works alongside examples for better understanding.
Aagam Vadecha

Last updated by Aagam 

Sep 23, 2024

Originally written by Joel

useState React

React is a free, open-source JavaScript frontend library that we can use to build frontend applications. Before React v16.8 in 2019, developers always used class components for data management (with states) and other operations like lifecycle methods, and functional components were only to be used for rendering UI.

Since the introduction of React Hooks in React v16.8, we can manage data via states in functional components and work with lifecycle methods. Over time, class components were outdated and deprecated in React. Functional components along with Hooks are the new standard way to write React components.

#State in React

Whenever an interaction happens, react components often need to change and show the latest data after an interaction. For instance, typing in a form should update the input field with whatever the user typed, clicking “next page” should change the page content, and clicking “Add contact” should add the new contact to the existing contact list.

To update the UI, components first need to “remember” these things: the current input value, the current page, and the current contact list. This kind of component-specific memory is called state.

For example:

import { Box, Button, Heading } from "@chakra-ui/react";
export default function CounterExample() {
let count = 0;
function handleClick() {
count = count + 1;
}
return (
<>
<Box p={8}>
<Button onClick={handleClick}> Increment </Button>
<Heading>{count}</Heading>
</Box>
</>
);
}

In this code above, we have defined a local variable count and an increment button, which tries to increment the count value by one every time it is clicked. However, if we try to run this code and click the increment button it doesn’t work as expected. This happens due to two reasons

  1. The value of a local variable does not persist across renders, meaning that on every re-render count will be re-initialized to 0.
  2. Local variables do not trigger re-renders, so when we click the Increment button, React would not detect a state change and would not re-render our component.

We need to have “state” here instead of the local variable to manage the memory of a component.

#useState Hook

The useState() hook:

  1. Allows us to obtain a state variable, this is a special variable that is capable of retaining data between renders.
  2. Provides us with a setter function to update the state variable and hence trigger a re-render of our component.

We can import the useState hook from react. The useState() hook takes in the initial value of the state variable as an argument and provides us with the state variable and the setter function. The variable could be of any data type, such as string, number, object, array, and more.

For Example:

import { useState } from "react";
const App = () => {
const [number, setNumber] = useState(1);
const [string, setString] = useState('John Doe')
const [object, setObject] = useState({name: 'johndoe'})
const [array, setArray] = useState([1,2,3])
return (
// ...
);
};

This setter function can be called anything, but it is a general practice to use the variable name with a prefix of set. For example - name, setName | count, setCount | and so on.

const [name, setName] = useState('John Doe')
const [count, setCount] = useState(0)
const [anything, setAnything] = useState({})

To fix our CounterExample component where we could not see the updates in the UI we can use the useState hook. Here’s how we can use it to fix the situation:

import { Box, Button, Heading } from "@chakra-ui/react";
import { useState } from "react";
export default function CounterExample() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<>
<Box p={8}>
<Button onClick={handleClick}>Increment </Button>
<Heading>{count}</Heading>
</Box>
</>
);
}

#Updater functions

Going a step further, we should understand that the setter function will always have access to the value of the state variable in the current render. Let us take the example of the counter component we have built above. Try adding some logs before and after calling the setCount and hit the increment button:

// ...
const [count, setCount] = useState(0);
function handleClick() {
console.log("Before Set Count", count);
setCount(count + 1);
console.log("After Set Count", count);
}
// ...

You might have expected it to print 1 in the After Set Count, but it logged a 0 there as well.

// ...
const [count, setCount] = useState(0);
function handleClick() {
console.log("Before Set Count", count); // Prints - Before Set Count 0
setCount(count + 1);
console.log("After Set Count", count); // Prints - After Set Count 0
}
// ...

This happens because in the entire execution context of the handleClick function, the value of count was initially 0 and the operations by setCount will take effect in the next render.

Next, let us take a look at this function below:

// ...
const [count, setCount] = useState(0);
function handleClick() {
console.log("Before Set Count", count);
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
console.log("After Set Count", count);
}
// ...

Okay, two questions arise here:

  1. What do you think will be printed in the logs?
  2. What will be the value of the count variable in the next render?

For 1, it will print 0 as the function will have access to the count value of the current render.

// ...
const [count, setCount] = useState(0);
function handleClick() {
console.log("Before Set Count", count); // Prints - Before Set Count 0
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
console.log("After Set Count", count); // Prints - After Set Count 0
}
// ...

For 2, the value of count in the next render will be 1 and not 3, even though we called setCount(count+1) thrice.

This is what actually happens, we are just calling setCount(0+1) thrice.

// ...
const [count, setCount] = useState(0);
function handleClick() {
console.log("Before Set Count", count);
setCount(count + 1); // setCount(0+1) = setCount(1)
setCount(count + 1); // setCount(0+1) = setCount(1)
setCount(count + 1); // setCount(0+1) = setCount(1)
console.log("After Set Count", count);
}
// ...

You may run into a situation where you want to access the latest value of a state variable and update it in that case you can use updater functions as shown below:

// ...
function handleClick() {
console.log("Before Set Count", count);
setCount(count => count + 1);
setCount(count => count + 1);
setCount(count => count + 1);
console.log("After Set Count", count);
}
// ...

As you can see, instead of passing a value to setCount we passed a function, this function gets the latest value of the variable as a parameter and returns an incremented value and this is how it will behave:

// ...
const [count, setCount] = useState(0);
function handleClick() {
console.log("Before Set Count", count); // Prints - Before Set Count 0
setCount(count => count + 1); // setCount(0 => 0+1) = setCount(1)
setCount(count => count + 1); // setCount(1 => 1+1) = setCount(2)
setCount(count => count + 1); // setCount(2 => 2+1) = setCount(3)
console.log("After Set Count", count); // Prints - After Set Count 0
}
// ...

#Using array/object as State

At times we need to store many things for a particular entity, for example - we can choose to have name, age, and hobby as state variables for a person.

const App = () => {
const [name, setName] = useState("John Doe");
const [age, setAge] = useState(20);
const [hobby, setHobby] = useState("Reading");
return (
// ...
);
};

Instead of creating three different state variables, it would be better to create an object that stores the state of a person. We can combine name, age, and hobby properties into an object state and use it as shown in the template.

const App = () => {
const [userDetails, setUserDetails] = useState({
name: "John Doe",
age: 20,
hobby: "Reading",
});
return (
<div>
<h1>{userDetails.name}</h1>
<p>
{userDetails.age} || {userDetails.hobby}
</p>
</div>
);
};

So far we have seen numbers, and strings as state variables, these JavaScript values are “immutable”, so if we replace them we can trigger a re-render.

For example:

const [distance, setDistance] = useState(5);
// ...
setDistance(15)

When we set the distance from 5 to 15, the value 5 itself doesn’t change. 5 is still 5

But when we do something as shown below, we are mutating the state, and the original userDetails object itself changes. This is known as a mutation. This is not allowed and would not lead React to re-render our component.

userDetails.name = 'Jane Doe'

It is important to remember that we cannot mutate a state variable of type objects/arrays. We always need to replace them entirely or use the spread operator.

// This is Incorrect
userDetails.name = 'Jane Doe'
// This is Correct
setState({
...userDetails,
name: 'Jane Doe'
})
// This is Correct
setState({
name: 'Jane Doe',
age: 20,
hobby: "Reading",
})

Similarly, we can use arrays to store some data as shown

const [todoList, setTodoList] = useState(["Buy Milk","Buy Bread","Fix Bugs"]);

When updating the array state, we must avoid methods like push, pop, shift, unshift, splice, reverse, and sort as these methods mutate the original array. Instead, we should use options like concat, spread syntax ([...arr]), filter, slice, and map as these methods return an entirely new array.

// This is Incorrect
todoList.push('Exercise')
// This is Correct
setState([
...todoList,
'Exercise'
])

#Caveats

useState is a hook, so just like any other hook, we should only use the useState() hook at the top level of our component: We should not use it inside any function, loop, nested function, or conditions. This helps React preserve and call hooks in the same order each time a component renders.

// Do not do this
if (condition) {
const [count, setCount] = useState()(0);
}
// Do not do this
for (let index = 0; index < 25; index++) {
let [count, setCount] = useState()(0);
}
// Do not do this
const nestedFn = () => () => {
const [count, setCount] = useState()(0);
};

#Conclusion

In this guide, we have learned what state is and why it is important, we learned about the useState() hook from React which helps us to manage a component’s memory. We also learned about the lifecycle of a state variable and how the new state value is enforced after a component’s re-render. Finally, we checked how to use objects and arrays as state variables and wrapped up by going through a few caveats about using hooks.

Blog Authors

Share with others

Sign up for our newsletter!

Be the first to know about releases and industry news and insights.