DEV Community

tingyuan
tingyuan

Posted on • Edited on

a new way to use state in react

In Reactjs, when you want to read or write the latest value of state data in your component, but do not want to specify them as dependencies(such as their change does not matter), you could use the custom hook function below.

Keep in mind that the only reason to specify dependencies in useEffect is because your effect callback need to re-run when anyone of the dependencies changes and the only reason why using useEffect is that you are not sure when the dependencies will change in the component.

export function useGetState(data) {
  const [val, setVal] = React.useState(data);
  const currentValRef = React.useRef(val);
  currentValRef.current = val;
  return React.useCallback((...args) => {
    if (args.length) {
      setVal(args[0]);
    } else {
      return currentValRef.current;
    }
  }, []);
}
Enter fullscreen mode Exit fullscreen mode

There is an example

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay